我已经看过一些帖子来获取google搜索的搜索结果数量,但到目前为止还没有满足我的需求。我想搜索一个带有空格的字符串,并得到几乎与在google中手动执行的搜索相同数量的结果。到目前为止,我的例程是
import requests
from bs4 import BeautifulSoup
test='just a teststring for the search'
r = requests.get('http://www.google.com/search',
params={'q':test}
)
soup = BeautifulSoup(r.text,"html5lib")
test=soup.find('div',{'id':'resultStats'}).text
例程给出32400个搜索结果,在谷歌页面的手动搜索85000,我做错了什么?!当我只搜索一个单词时,偏差要小得多。
发布于 2021-08-20 05:58:32
它只是在每次发送请求时总是不同。谷歌搜索结果在不同的计算机上是不同的,他们希望并期望每个人的搜索结果都是不同的。这取决于很多因素。
就从机器人(脚本)发送请求而言,结果可能是相同的,但不是所有时间都是相同的。
例如:
>>> soup.select_one('#result-stats nobr').previous_sibling
'About 4,100,000,000 results'
# in fact, there're was 4,000,000 results in my browser
import requests, lxml
from bs4 import BeautifulSoup
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
params = {
"q": "step by step guide how to prank google",
"gl": "us",
"hl": "en"
}
response = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(response.text, 'lxml')
number_of_results = soup.select_one('#result-stats nobr').previous_sibling
print(number_of_results)
-----
# About 7,800,000 results
或者,您可以使用SerpApi中的Google Organic Results API。这是一个免费套餐的付费API。
主要区别在于,您只需要遍历结构化的JSON,而不需要弄清楚如何提取某些元素并从头开始编写所有内容。不需要维护解析器。
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "step by step guide how to prank google",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
result = results["search_information"]['total_results']
print(result)
-----
# 7800000
免责声明,我为SerpApi工作。
https://stackoverflow.com/questions/49665726
复制相似问题