python - 使用 Python 请求和 Beautiful Soup 从 span 标签中检索数字

标签 python beautifulsoup

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

在此示例中,我尝试获取数字 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>

我不知道为什么没有显示该值。预先感谢您的任何帮助。

最佳答案

页面,特别是评论的数量,确实涉及要加载和显示的 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}}

关于python - 使用 Python 请求和 Beautiful Soup 从 span 标签中检索数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41528941/

相关文章:

javascript - 有没有办法用beautiful soup过滤掉JavaScript中嵌入的product id

python - 关于使用 py bs4 进行网页抓取的问题

python - 拆分/提取数据框中的部分列 - python

python - 模块未找到错误 : No module named 'utils'

python-3.x - 如何获得BeautifulSoup标签的所有直接子级?

python - Beautifulsoup 如何找到所有工作

Python 使用原始文件名 Mechanize 下载文件

python - 如何从 python 中的 datetime.now() 获取分钟、秒和毫秒?

python - 为什么 python 整数缓存范围 [-5, 256] 不能在所有平台上以类似的方式工作?

python - 如何在 linux 机器上更改 python 的默认版本?(不仅仅是符号链接(symbolic link))