我需要遍历 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”元素(206,226)的 x1 值。帮助很大!
编辑:我试过:
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)
获取元素的文本。