python - 如何使用没有类的 BeautifulSoup 提取值

标签 python parsing python-2.7 html-parsing beautifulsoup

html代码:

<td class="_480u">
    <div class="clearfix">
        <div>
            Female
        </div>
    </div>
</td>

我想要值“Female”作为输出。

我尝试了 bs.findAll('div',{'class':'clearfix'}) ; bs.findAll('tag',{'class':'_480u'}) 但是这些类遍布我的 html 代码,输出是一个大列表。我想在我的搜索中加入 {td --> class = ".."and div --> class = ".."},这样我得到的输出是 Female。我该怎么做?

谢谢

最佳答案

使用stripped_strings属性:

>>> from bs4 import BeautifulSoup
>>>
>>> html = '''<td class="_480u">
...     <div class="clearfix">
...         <div>
...             Female
...         </div>
...     </div>
... </td>'''
>>> soup = BeautifulSoup(html)
>>> print ' '.join(soup.find('div', {'class': 'clearfix'}).stripped_strings)
Female
>>> print ' '.join(soup.find('td', {'class': '_480u'}).stripped_strings)
Female

或将类指定为空字符串(或None)并使用string 属性:

>>> soup.find('div', {'class': ''}).string
u'\n            Female\n        '
>>> soup.find('div', {'class': ''}).string.strip()
u'Female'

关于python - 如何使用没有类的 BeautifulSoup 提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18443694/

相关文章:

python - 将用户输入附加到循环中的列表

python - 仅从 pyspark 中的 Spark DF 选择数字/字符串列名称

Java 十进制格式 - 与给定的一样多的精度

ruby 将定界字符串数组转换为散列

python - 覆盖 `from my_module import ...`

python - zyBooks 上的程序输出下显示输入提示。这是我的错误吗?

python - 是否可以在 Dataframe 中使用 Pandas Overlap?

python - 如何解决python2.7中的名称错误

xml - 用于 AS3/Flex/Adobe AIR 应用程序的流解析器 (JSON/XML)

OS X 上的 Python 2.7 : TypeError: 'frozenset' object is not callable on each command