簡體   English   中英

BeaufifulSoup,標簽名稱中帶有“-”的標簽的lxml導航?

[英]BeaufifulSoup, lxml navigation for tag with “-” in the tag name?

<body>
<response status="success">
<policy>
<shared/>
<panorama>
<address>
    <entry name="text">
    <tag1></tag1>>
    <tag2></tag2>
    </entry>>
</address>
<service>
....
</service>
<pre-rulebase>
</pre-rulebase>
<security>
<rules>
    <entry name="some text">
    <tag1>text</tag1>>
    <tag2>text</tag2>
    </entry>
    <entry name="more text">
    <tag1>text</tag1>
    <tag2>text</tag2>
    </entry>
    ...
    </rules>
</security>
<post-rulebase>
    <entry name="some text">
    <tag1>text</tag1>>
    <tag2>text</tag2>
    </entry>
    <entry name="more text">
    <tag1>text</tag1>>
    <tag2>text</tag2>
    </entry>
</post-rulebase>
</panorama>
</policy>
</response> 
</body>

你好,

我正在嘗試使用 Python BeautifulSoup 和 lxml 解析以上 xml 文件。 通常我使用'.'導航到元素。 例如

from bs4 import BeautifulSoup
with open('sample.xml', 'r') as xml_file:
    soup = BeautifulSoup(xml_file, 'lxml')

for item in soup.body.response.policy.panorama.address.find('entry'):
    <some code action>

我的問題是通過上面導航“”和“”等標簽。 由於標簽名稱中有“-”,因此“。” 導航不起作用。 此外,由於子標簽具有相同的名稱,我不能使用它直接查找。 如何導航和遍歷“即”標簽下的標簽?

您可能可以這樣做:

from lxml import etree
rules = """[your xml, fixed]"""
doc = etree.XML(rules)
for i in doc.xpath('//post-rulebase//entry'):
    print(i.tag,i.attrib['name'])
    for t in i.xpath('.//*'):
        print(t.tag,t.text)

Output:

entry some text
tag1 text
tag2 text
entry more text
tag1 text
tag2 text

另一種方法。

from simplified_scrapy import SimplifiedDoc, req, utils
html = '''
<address>
    <entry name="text">
    <tag1></tag1>>
    <tag2></tag2>
    </entry>>
</address>
<service>
....
</service>
<post-rulebase>
    <entry name="some text">
    <tag1>text</tag1>>
    <tag2>text</tag2>
    </entry>
    <entry name="more text">
    <tag1>text</tag1>>
    <tag2>text</tag2>
    </entry>
</post-rulebase>'''
doc = SimplifiedDoc(html)
entry = doc.select('post-rulebase').entry
print(entry)
print(entry.children.text)

結果:

{'name': 'some text', 'tag': 'entry', 'html': '\n    <tag1>text</tag1>>\n    <tag2>text</tag2>\n    '}
['text', 'text']

這里有更多例子: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM