Python 通过BS4发出提取特定XML值的命令,并将其写入dataframe

Python 通过BS4发出提取特定XML值的命令,并将其写入dataframe,python,xml,pandas,beautifulsoup,Python,Xml,Pandas,Beautifulsoup,我是Python新手,正在尽最大努力收集一些XML数据。 到目前为止,我使用find和get方法使它能够用于“普通”XPath和属性,但我正在努力解决最后一点 这是XML的一个示例部分: <root> <job> <othernodes>text</othernodes> <advertiser>INPUT I WANT <node2>text</node2> <node3>text&

我是Python新手,正在尽最大努力收集一些XML数据。 到目前为止,我使用
find
get
方法使它能够用于“普通”XPath和属性,但我正在努力解决最后一点

这是XML的一个示例部分:

<root>
<job>
<othernodes>text</othernodes>
<advertiser>INPUT I WANT
    <node2>text</node2>
    <node3>text</node3>
</advertiser>
<othernodes>text</othernodes>
</job>
如果打印结果,则不会为节点广告客户返回任何值。 我试着解决这个问题,但找不到解决办法。
谢谢

下面是您需要的代码

import xml.etree.ElementTree as ET

XML = '''<root>
    <job>
    <othernodes>text</othernodes>
    <advertiser>add1
        <node2>text</node2>
        <node3>text</node3>
    </advertiser>
    <othernodes>text</othernodes>
    </job>
    <job>
    <othernodes>text</othernodes>
    <advertiser>add2
        <node2>text</node2>
        <node3>text</node3>
    </advertiser>
    <othernodes>text</othernodes>
    </job>
</root>'''
root = ET.fromstring(XML)
data = [a.text.strip() for a in root.findall('.//advertiser')]
print(data)

无需使用
ElementTree
,可以使用
BeautifulSoup

尝试调用返回第一个匹配项的方法:

from bs4 import BeautifulSoup

xml = """<root>
<job>
<othernodes>text</othernodes>
<advertiser>INPUT I WANT
    <node2>text</node2>
    <node3>text</node3>
</advertiser>
<othernodes>text</othernodes>
</job>"""

soup = BeautifulSoup(xml, "html.parser")

print([soup.find("advertiser").find_next(text=True).strip()])

# Or using `find_all()`
# print([tag.find_next(text=True).strip() for tag in soup.find_all("advertiser")])

如果使用XPath,可能会更干净?
['add1', 'add2']
from bs4 import BeautifulSoup

xml = """<root>
<job>
<othernodes>text</othernodes>
<advertiser>INPUT I WANT
    <node2>text</node2>
    <node3>text</node3>
</advertiser>
<othernodes>text</othernodes>
</job>"""

soup = BeautifulSoup(xml, "html.parser")

print([soup.find("advertiser").find_next(text=True).strip()])

# Or using `find_all()`
# print([tag.find_next(text=True).strip() for tag in soup.find_all("advertiser")])
['INPUT I WANT']