要获得美国或英国的结果,您可以使用 gl 查询参数,它代表 用于 Google 搜索的国家/地区。
通过query params:
params = {
'q': 'minecraft',
'gl': 'us', # country to search from
'hl': 'en', # language
}
requests.get('URL', params=params)
最终出现的下一个问题是您没有指定user-agent。您需要发送user-agent,这将作为“真正的”用户访问。当机器人或浏览器发送虚假的user-agent 字符串以宣布自己为不同的客户端时。因为default requests user-agent is python-requests。
您可以在我写的关于 how to reduce the chance of being blocked while web scraping 的博文中了解更多信息。
通过user-agent:
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'
}
requests.get('URL', headers=headers)
代码和example in the online IDE:
from bs4 import BeautifulSoup
import requests, lxml
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': 'minecraft',
'gl': 'us', # United States results
'hl': 'en',
}
html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')
for result in soup.select('.tF2Cxc'):
title = result.select_one('.DKV0Md').text
link = result.select_one('.yuRUbf a')['href']
print(title, link, sep='\n')
或者,您可以使用来自 SerpApi 的 Google Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。
您的情况的不同之处在于,此代码通常更易于阅读,如果 HTML 中的某些内容发生更改,则无需随着时间的推移对其进行维护(因为有专门的开发团队负责处理它 em>),找出如何绕过 Google 或其他搜索引擎的屏蔽。
要集成的代码:
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "tesla",
"hl": "en",
"gl": "us", # country to search from
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results["organic_results"]:
print(result['title'])
print(result['link'])
免责声明,我为 SerpApi 工作。