如何使用 Python 中的 BeautifulSoup 从 div 获取对象?

How to get objects from div with BeautifulSoup in Python?

我对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() returns 属性值,不是元素下包含的文本。

您可以获取直接包含在带有 Element.string attribute, or all contained text (recursively) with the 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