python - 如何循环Beautiful Soup元素来获取属性值

标签 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)

从元素中获取文本。

最佳答案

这似乎可行,尽管不是那么优雅:

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/

相关文章:

python - 如何将子项目与 Pandas 数据框中的父项目相关联?

PHP - 如何读取私有(private) XML 文件?

python - 使用 BeautifulSoup 循环遍历表行

python - 在 Solaris 上使用 Python 终止进程时出现问题

Python:Python 函数相当于 Python 对象吗?

java - 使用 jackson 将具有重复元素的 XML 转换为 JSON

java - 如何使用 iBatis

python - 从文章中提取文本,如何过滤div中的标签?

python - Beautifulsoup 网络爬虫问题

python - 导入数据显示0000-00-00格式