【问题标题】:How to extract values with BeautifulSoup with no class如何在没有类的情况下使用 BeautifulSoup 提取值
【发布时间】:2013-08-28 22:00:47
【问题描述】:

html代码:

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

我想要值“女性”作为输出。

我试过bs.findAll('div',{'class':'clearfix'})bs.findAll('tag',{'class':'_480u'}) 但是这些类都在我的 html 代码中,输出是一个大列表。我想在我的搜索中合并 {td --> class= ".." 和 div --> class= ".."},这样我就得到了女性的输出。我该怎么做?

谢谢

【问题讨论】:

    标签: python parsing python-2.7 html-parsing beautifulsoup


    【解决方案1】:

    使用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'
    

    【讨论】:

    • 感谢您的快速回答。 :)
    • @user1946217 如果他的回答有用,请务必将其标记为正确!
    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多