使用 BeautifulSoup 获取搜索结果编号
Get Search Results Number Using 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
或 requests_html
。确实有很多模块可以做到这一点。
现在,我们在 table 上还有另一个选项,可以跟踪数据的呈现位置。我能够找到用于从 back-end
API
检索数据并将其呈现给用户端的 XHR 请求。
You can get the XHR
request by open Developer-Tools and check Network and check XHR/JS
requests made depending of the type of call such as 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}
Note: you can play with q=toronto
to query another keyword
, and size=10
to define the size of output.
我正在尝试在 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
或 requests_html
。确实有很多模块可以做到这一点。
现在,我们在 table 上还有另一个选项,可以跟踪数据的呈现位置。我能够找到用于从 back-end
API
检索数据并将其呈现给用户端的 XHR 请求。
You can get the
XHR
request by open Developer-Tools and check Network and checkXHR/JS
requests made depending of the type of call such asfetch
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}
Note: you can play with
q=toronto
to query anotherkeyword
, andsize=10
to define the size of output.