您收到了一个完全不同的 HTML,其中包含不同的元素和选择器,因此输出为空。谷歌阻止你的请求的原因是因为默认的requests user-agent 是python-requests 并且谷歌理解它并阻止它。 Check what's your user-agent.
User-agent 让我们识别浏览器、它的版本号和它的主机操作系统,它在 Web 上下文中代表一个人(浏览器),让服务器和网络对等方识别它是否是机器人。
有时您可以收到带有不同选择器的不同 HTML。
您可以将 URL 参数作为dict() 传递,这样更具可读性,并且请求会自动为您完成所有操作(将user-agent 添加到headers 中也是如此):
params = {
"q": "My query goes here"
}
requests.get("YOUR_URL", params=params)
如果您想获得第一个链接,请改用select_one()。
代码和full example in the online IDE:
from bs4 import BeautifulSoup
import requests
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": "My query goes here"
}
html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')
link = soup.select_one('.yuRUbf a')['href']
print(link)
# https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html
或者,您可以使用来自 SerpApi 的 Google Organic Results API 来做同样的事情。这是一个带有免费计划的付费 API。
您的情况不同的是,您只需要从 JSON 字符串中提取所需的数据,而不是弄清楚如何从 Google 提取、维护或绕过块。
要集成的代码:
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "My query goes here",
"hl": "en",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
# [0] means first index of search results
link = results['organic_results'][0]['link']
# https://dev.mysql.com/doc/refman/8.0/en/entering-queries.html
免责声明,我为 SerpApi 工作。