我需要迭代 Beautiful Soup 元素并获取属性值: 对于 XML 文档:
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<Page x1="71" y1="120" x2="527" y2="765" type="page" chunkCount="25"
pageNumber="1" wordCount="172">
<Chunk x1="206" y1="120" x2="388" y2="144" type="unclassified">
<Word x1="206" y1="120" x2="214" y2="144" font="Times-Roman" style="font-size:22pt">K</Word>
<Word x1="226" y1="120" x2="234" y2="144" font="Times-Roman" style="font-size:22pt">O</Word>
</Chunk>
</Page>
</Document>
我想获取“Word”元素的 x1 值 (206,226)。 非常感谢!
编辑: 我尝试过:
for i in soup.page.chunk:
i.word['x1']
返回错误:
File "C:\Python26\lib\site-packages\BeautifulSoup.py", line 473, in __getattr__
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
AttributeError: 'NavigableString' object has no attribute 'word'
同时:
soup.page.chunk.word['x1']
工作正常...并且:
for i in soup.page.chunk:
i.findNext(text=True)
从元素中获取文本。
最佳答案
这似乎可行,尽管不是那么优雅:
for word in soup.page.chunk.find_all('word'):
print word['x1']
嵌套的 find_all 也应该可以工作。但可能最好使用类似 css 的选择(soupselect 或来自 lxml)。
基本上,如果我没记错的话,soup.page.chunk
是一个节点,soup 标签。因此,如果你想要迭代,你必须调用 find_all。
更新。不同的方法可以是 find_all('word')
,然后根据 word.parent.name == 'smth'
[!] 在 BeautifulSoup3(不是 bs4)中,它应该是 findAll
而不是 find_all
关于python - 如何循环Beautiful Soup元素来获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862699/