python - 如何从内部带有 <span> 的 <dt> 标签中获取文本?

标签 python web-scraping beautifulsoup

我正在尝试从 <dt> 中提取文本带有 <span> 的标签www.uszip.com 内:

这是我想要得到的示例:

<dt>Land area<br><span class="stype">(sq. miles)</span></dt>
<dd>14.28</dd>

我想要14.28脱离标签。这就是我目前正在采取的方法:

注:soup是整个网页源代码的BeautifulSoup版本:

soup.find("dt",text="Land area").contents[0]

但是,这给了我一个

AttributeError: 'NoneType' object has no attribute 'contents'

我尝试了很多方法,但不知道如何解决这个问题。此方法适用于该页面上的一些其他数据,例如:

<dt>Total population</dt>
<dd>22,234<span class="trend trend-down" title="-15,025 (-69.77% since 2000)">&#9660;</span></dd>

使用soup.find("dt",text="Total population").next_sibling.contents[0]在此返回'22,234' .

我应该如何尝试首先识别正确的标签,然后从中获取正确的数据?

最佳答案

不幸的是,您无法仅根据所包含的文本将标签与文本和嵌套标签相匹配。

你必须循环遍历所有 <dt> 没有文字:

for dt in soup.find_all('dt', text=False):
    if 'Land area' in dt.text:
        print dt.contents[0]

这听起来违反直觉,但.string此类标签的属性为空,这就是 BeautifulSoup 所匹配的内容。 .text包含所有嵌套标签组合中的所有字符串,并且不匹配。

您还可以使用custom function进行搜索:

soup.find_all(lambda t: t.name == 'dt' and 'Land area' in t.text)

本质上使用封装在 lambda 中的过滤器进行相同的搜索功能。

关于python - 如何从内部带有 <span> 的 <dt> 标签中获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725787/

相关文章:

python - 字典问题(TypeError : string indices must be integers)

python - 我可以将事件与 Firebase 的 REST api 一起使用吗?

python - Numpy.delete 删除 3 个项目,但仅删除 2 个匹配条件

ruby - 带有过滤器的 Nokogiri next_element

python - 使用选择器获取不同 "h"标签的内容时遇到问题

python - 有没有办法将搜索选项添加到 Bokeh 中的多选或选择小部件?

python - Scrapy 没有按照 allowed_domains 过滤结果

xpath - 从@href属性获取值

r - 在 R 中从 opensubtitles.org 网页抓取字幕

python - 使用 Selenium 和 Beautifulsoup 解析 Airdna map 悬停在文本上