我正在尝试从 <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)">▼</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/