gpt4 book ai didi

python - 如何在 Python 中使用 BeautifulSoup 从 div 获取对象?

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:33 25 4
gpt4 key购买 nike

我对 BeautifulSoup 不是很熟悉。我有这样的 html 代码(这只是其中的一部分):

<div class="central-featured-lang lang1" lang="en">
<a class="link-box" href="//en.wikibooks.org/">
<strong>English</strong><br>
<em>Open-content textbooks</em><br>
<small>51 000+ pages</small></a>
</div>

关于我应该得到的输出(对于其他语言):

English: 51 000+ pages.

我试过类似的方法:

for item in soup.find_all('div'):
print item.get('class')

但这行不通。你能帮我吗,或者至少能找到解决方案?

最佳答案

item.get() 返回属性值,而不是元素下包含的文本。

您可以使用 Element.string attribute 获取直接包含在元素中的文本,或所有包含的文本(递归地)与 Element.get_text() method .

在这里,我将搜索具有 lang 属性的 div 元素,然后使用包含的元素来查找字符串:

for item in soup.find_all('div', lang=True):
if not (item.strong and item.small):
continue
language = item.strong.string
pages = item.small.string
print '{}: {}'.format(language, pages)

演示:

>>> from bs4 import BeautifulSoup
>>> sample = '''\
... <div class="central-featured-lang lang1" lang="en">
... <a class="link-box" href="//en.wikibooks.org/">
... <strong>English</strong><br>
... <em>Open-content textbooks</em><br>
... <small>51 000+ pages</small></a>
... </div>
... '''
>>> soup = BeautifulSoup(sample)
>>> for item in soup.find_all('div', lang=True):
... if not (item.strong and item.small):
... continue
... language = item.strong.string
... pages = item.small.string
... print '{}: {}'.format(language, pages)
...
English: 51 000+ pages

关于python - 如何在 Python 中使用 BeautifulSoup 从 div 获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com