首页 > 解决方案 > 使用 BeautifulSoup 获取搜索结果编号

问题描述

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

网页上的源代码是

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

"Displaying results 1-10 out of 2208 for"

<strong>toronto</strong>

</div>

如屏幕截图 1 所示:

截图 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>

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

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

标签: pythonhtmlwebbeautifulsoupweb-crawler

解决方案


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

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

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

您可以XHR通过打开Developer-Tools并检查Network并检查XHR/JS根据调用类型发出的请求来获取请求,例如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定义输出的大小。


推荐阅读