【问题标题】:Python/Beautiful Soup – finding string within heading within div [duplicate]Python/Beautiful Soup – 在 div 的标题中查找字符串 [重复]
【发布时间】:2013-02-28 16:05:39
【问题描述】:

作为 Python 新手,我花了大约一个小时试图从 div 内的标题中找到一个带有 Python 2.7.x 和 Beautiful Soup 的字符串:

import urllib2
from bs4 import BeautifulSoup

request = urllib2.Request("http://somerandomurl.org")
response = urllib2.urlopen(request)
soup = BeautifulSoup(response)

HTML 文件如下所示:

<div class="ABC">
    <h1>My string</h1>
</div>

我无法描述我在这里尝试过的Beautiful Soup Documentation 的所有方式(包括print soup.div('ABC').h1 ...),但我认为我在阅读时遇到了严重错误。谢谢你的帮助。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你想要的:

    soup.find('div', class_='ABC').h1
    

    这会找到 first 带有ABC 类的div 标记,然后遍历其中的第一个H1 标记:

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('''
    ... <div class="ABC">
    ...     <h1>My string</h1>
    ... </div>
    ... ''')
    >>> soup.find('div', class_='ABC').h1
    <h1>My string</h1>
    

    【讨论】:

    • 谢谢。在我的示例中,这给了我以下错误:“AttributeError: 'NoneType' object has no attribute 'h1'”
    • @lejonet8: 那么你确实没有在你的输入 HTML 中有一个具有该类的 div。
    • XYZ

      原来的类名包含一个 - 这可能是个问题吗?
    • @lejonet8:soup.find('div') 会返回什么吗? soup.find(class_='ABC') 是否匹配任何内容?您需要缩小范围。不,类名中的破折号 (-) 没有区别。
    • 可以,可以使用正则表达式匹配类; import re 然后 .find('div', class_=re.compile(r'ABC\d')) 将匹配所有这些。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签