如何遍历Beautiful Soup元素以获取属性值

时间:2012-06-02 13:33:42

标签: python xml beautifulsoup

我需要遍历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)

获取元素的文本。

1 个答案:

答案 0 :(得分:2)

虽然不是那么优雅但似乎有效:

for word in soup.page.chunk.find_all('word'):
    print word['x1']

嵌套的find_all也应该有用。但是使用类似CSS的选择(汤选或来自lxml)可能更好。

基本上如果我没有弄错soup.page.chunk是一个节点,汤标签。因此,如果你想要迭代,你必须调用find_all。

UPD。不同的方法可以是find_all('word'),然后根据word.parent.name == 'smth'

等条件进行过滤 在BeautifulSoup3(而非bs4)中

[!]它应该是findAll而不是find_all