【问题标题】:Get Search Results Number Using BeautifulSoup使用 BeautifulSoup 获取搜索结果编号
【发布时间】:2020-03-21 23:21:42
【问题描述】:

我正在尝试在 Python 中使用 BeautifulSoup 来获取 CNN 中的搜索结果总数。

网页上的源代码是

<div class="cnn-search__results-count">

"Displaying results 1-10 out of 2208 for"

<strong>toronto</strong>

</div>

如截图1所示:

我写的代码是:

from bs4 import BeautifulSoup

import requests

url_cnn = 'https://www.cnn.com/search?q=toronto'

response_cnn = requests.get(url_cnn)

html_cnn = response_cnn.text

soup = BeautifulSoup(html_cnn, 'html.parser')

cnn = (soup.find('div', {"class": "cnn-search__results-count"}))

print(cnn)

但是,我只得到

<div class="cnn-search__results-count"></div>

中间的所有内容都不见了。

有谁知道如何解决这个问题?非常感谢!

【问题讨论】:

  • 我建议添加与互联网和网站相关的标签。了解python和beautifulsoup可能还不够。
  • 感谢永利夫!我添加了一些新标签

标签: python html web beautifulsoup web-crawler


【解决方案1】:

网站加载了JavaScript 事件,该事件在页面加载后动态呈现其数据。

requests 库将无法即时渲染 JavaScript。所以你可以使用seleniumrequests_html。确实有很多模块可以做到这一点。

现在,我们在表格上确实有另一个选项,可以跟踪数据的呈现位置。我能够找到 XHR 请求,该请求用于从 back-end API 检索数据并将其呈现给用户端。

您可以通过打开Developer-Tools 并检查Network 和检查XHR/JS 请求来获取XHR 请求,具体取决于调用类型,例如fetch

import requests
import json


r = requests.get("https://search.api.cnn.io/content?q=toronto&size=10").json()

data = json.dumps(r, indent=4)

# print(data) #to see the full output in nice format.

# print(r.keys()) # to see the keys of the JSON dict

print(r["meta"])

输出:

{'start': 1, 'end': 10, 'total': 10, 'of': 2208, 'maxScore': None, 'duration': 
55}

注意:您可以使用q=toronto 来查询另一个keyword,并使用size=10 来定义输出的大小。

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2020-10-09
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多