python - 使用 BeautifulSoup 获取搜索结果编号
问题描述
我正在尝试在 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>
中间的所有内容都不见了。
有谁知道如何解决这个问题?非常感谢!
解决方案
该网站加载了JavaScript
事件,该事件在页面加载后动态呈现其数据。
requests
库将无法JavaScript
即时渲染。所以你可以使用selenium
or 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
定义输出的大小。
推荐阅读
- elasticsearch - 布尔查询格式错误
- matlab - 最小二乘的收敛准则
- flutter - 如何在 Flutter 中创建两个相同的实例小部件
- sap-cloud-sdk - 如何最好地模拟 S4 端点来进行性能测试(负载测试)?
- python - 熊猫读取一些 xlsx 文件但不读取其他文件
- linux - 未能安装 linux (debian) 导致“找不到 CD ROM”
- node.js - 如何为每个nodejs项目保留不同或特定的firebase帐户
- spring - org.springframework.dao.DataIntegrityViolationException:POSTGRESQL
- c# - 无法让嵌套对象在 DataGrid 中显示为嵌套 Datgrid 行
- oracle - 在 Oracle SQL*Plus 中退出会话后回滚