【问题标题】:How to grab an distinct attribute using beautifulsoup from an xml file?如何使用 Beautifulsoup 从 xml 文件中获取不同的属性?
【发布时间】:2022-08-19 03:35:48
【问题描述】:

这是我要提取的数据:

<messages>

    <message type=\"General\" code=\"ER\">SECURITY ALERT message(s) found.</message>

    <message type=\"General\">ORDER NUMBER: 7575757</message>

</messages>

我只是想获取订单号:7575757

我尝试了几种获取此属性的方法,但均未成功。

第一次尝试:

def parseTestID(testid):
    dict = {\'ORDER NUMBER\': testid.split(\" \")[0].split(\":\")[0]}
    return dict

 


parsedData= []
    
for element in bs_data.find_all(\"messages\"):
    for message in element.find_all(\"message\"):
        dict = {\'type\': message[\'type\'], \'ORDER NUMBER\': parseTestID(message.string)[\'ORDER NUMBER\']}
            # append dictionary to list
        parsedData.append(dict)

    # return list
    print(parsedData)

输出:

[{\'type\': \'General\', \'ORDER NUMBER\': \'SECURITY\'}, {\'type\': \'General\', \'ORDER NUMBER\': \'ORDER\'}]

第二次尝试:

for element in bs_data.find_all(\"messages\"):
    for message in element.find_all(\"message\"):
        print(message.text)

输出:

    SECURITY ALERT message(s) found.
    ORDER NUMBER: FA3JZ0P

我觉得我很接近但不太确定如何抓住这个特定的属性。

    标签: python xml parsing beautifulsoup attributes


    【解决方案1】:

    您可以通过以下方式获得该号码:

    from bs4 import BeautifulSoup
    import re
    html = '''
    <messages>
    
        <message type="General" code="ER">SECURITY ALERT message(s) found.</message>
    
        <message type="General">ORDER NUMBER: 7575757</message>
    
    </messages>
    '''
    soup = BeautifulSoup(html, 'html.parser')
    desired_info = soup.find('message', string = re.compile('ORDER NUMBER:')).text.split(':')[1].strip()
    print(desired_info)
    

    这将只返回数字:

    7575757
    

    如果你想要完整的字符串,那么你可以跳过上面的分割字符串。 BeautifulSoup 文档(此时我强烈建议仔细阅读):https://beautiful-soup-4.readthedocs.io/en/latest/index.html

    【讨论】:

      【解决方案2】:

      另一种解决方案,没有re

      num = soup.select_one('message:-soup-contains("ORDER NUMBER")').text.split()[-1]
      print(num)
      

      印刷:

      7575757
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 2021-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 2019-10-15
        相关资源
        最近更新 更多