我怎样才能获得文本出来一个< D​​T>跨度>在一个与所述标签;内? [英] How can I get text out of a <dt> tag with a <span> inside?

查看:230
本文介绍了我怎样才能获得文本出来一个< D​​T>跨度>在一个与所述标签;内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从里面&LT提取文本; DT> 带标签的<跨度> 里面的www.uszip.com:

I'm trying to extract the text from inside a <dt> tag with a <span> inside on www.uszip.com:

下面是什么,我试图让一个例子:

Here is an example of what I'm trying to get:

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

我想要得到的 14.28 出标签。这是我当前如何接近它:

I want to get the 14.28 out of the tag. This is how I'm currently approaching it:

请注意:汤是整个网页的源$ C ​​$ C的BeautifulSoup版本:

Note: soup is the BeautifulSoup version of the entire webpage's source code:

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

不过,这是给我一个

However, this is giving me a

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

我已经尝试了很多事情,我不知道如何处理这一点。此方法适用于其他一些数据在此页面上,如:

I've tried a lot of things and I'm not sure how to approach this. This method works for some of the other data on this page, like:

<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,文本=总人口)。next_sibling.contents [0] 这个返回 '22,234

我应该如何首先尝试找出正确的标签,然后得到正确的数据出来吗?

How should I try to first identify the correct tag and then get the right data out of it?

推荐答案

不幸的是,你不能匹配文本和嵌套的标签标记的基础上,仅包含的文本。

Unfortunately, you cannot match tags with both text and nested tags, based on the contained text alone.

您不得不遍历所有的&LT; D​​T&GT; 没有的文本:

You'd have to loop over all <dt> without text:

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

这听起来违反直觉,但对于这样的标签 .string 属性是空的,而这正是BeautifulSoup反对匹配。 的.text 包含所有嵌套的标签组合的所有字符串,那就是不反对匹配。

This sounds counter-intuitive, but the .string attribute for such tags is empty, and that is what BeautifulSoup is matching against. .text contains all strings in all nested tags combined, and that is not matched against.

您也可以使用自定义函数做搜索:

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

基本上做同样的搜索,使用封装在的λ函数的过滤器。

这篇关于我怎样才能获得文本出来一个&LT; D​​T&GT;跨度&gt;在一个与所述标签;内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆