【问题标题】:Retrieve a number from a span tag, using Python requests and Beautiful Soup使用 Python 请求和 Beautiful Soup 从 span 标签中检索一个数字
【发布时间】:2017-01-08 02:44:36
【问题描述】:

我是 python 和 html 的新手。我正在尝试使用请求和 BeautifulSoup 从页面中检索 cmets 的数量。

在此示例中,我试图获取数字 226。这是我在 Chrome 中检查页面时看到的代码:

<a title="Go to the comments page" class="article__comments-counts" href="http://www.theglobeandmail.com/opinion/will-kevin-oleary-be-stopped/article33519766/comments/">
    <span class="civil-comment-count" data-site-id="globeandmail" data-id="33519766" data-language="en">
    226
    </span>
    Comments
</a>

当我从 URL 请求文本时,我可以找到代码,但 span 标签之间没有内容,没有 226。这是我的代码:

import requests, bs4

url = 'http://www.theglobeandmail.com/opinion/will-kevin-oleary-be-stopped/article33519766/'
r = requests.get()
soup = bs4.BeautifulSoup(r.text, 'html.parser')

span = soup.find('span', class_='civil-comment-count')

返回这个,和上面一样,但是没有226。

<span class="civil-comment-count" data-id="33519766" data-language="en" data-site-id="globeandmail">
</span>

我不知道为什么该值没有出现。提前感谢您的任何帮助。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    页面,特别是 cmets 的数量,确实涉及要加载和显示的 JavaScript。但是,你不必使用 Selenium,向它背后的 API 发出请求:

    import requests
    
    with requests.Session() as session:
        session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36"}
    
        # visit main page
        base_url = 'http://www.theglobeandmail.com/opinion/will-kevin-oleary-be-stopped/article33519766/'
        session.get(base_url)
    
        # get the comments count
        url = "https://api-civilcomments.global.ssl.fastly.net/api/v1/topics/multiple_comments_count.json"
        params = {"publication_slug": "globeandmail",
                  "reference_language": "en",
                  "reference_ids": "33519766"}
        r = session.get(url, params=params)
        print(r.json())
    

    打印:

    {'comment_counts': {'33519766': 226}}
    

    【讨论】:

      【解决方案2】:

      此页面使用 JavaScript 获取评论编号,这是禁用 JavaScript 后页面的外观:

      您可以在 Chrome 的开发者工具中找到包含数字的真实 url:

      您可以使用@alecxe 代码模拟请求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-31
        • 1970-01-01
        • 2017-06-30
        • 1970-01-01
        • 2021-01-24
        • 1970-01-01
        相关资源
        最近更新 更多