1。它将从 HTML 返回所有 <h3> 元素,包括诸如“相关搜索、视频、人们也询问”部分之类的文本,在这种情况下,这不是您要查找的内容。
gresults = soup.findAll('h3')
2。这种搜索方法在某些情况下很好,但在特定情况下不是首选,因为您这样做有点盲目或成像,如果其中一个 .parent 节点(元素)将消失,则会引发错误。
不要执行所有这些操作,而是调用适当的 CSS 选择器(更多内容在下面),而不执行此方法链接可能不可读(如果有很多父节点) .
result.parent.parent.find_all()
3。 get('href') 可以工作,但是您会得到这样的 URL,因为没有传递 user-agent 来请求 headers,这是“充当”真实用户访问所必需的。当user-agent 被传递给请求headers 时,您将得到一个正确的URL(我不知道这种行为的正确解释)。
如果在使用requests 库时没有将user-agent 传递给请求headers,则默认为python-requests,因此Google 或其他搜索引擎(网站)知道这是一个bot/script,并且可能会阻止请求或收到的 HTML 将与您在浏览器中看到的不同。检查what's your user-agent。 List of user-agents.
通过user-agent 请求headers:
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582"
}
requests.get('URL', headers=headers)
要使其正常工作,您需要:
1。通过调用特定的CSS 选择器来查找包含所有需要数据的容器(查看SelectorGadget 扩展名)。 CSS selectors reference.
将容器想象成一个盒子,里面装着东西,您可以通过指定要获取的项目来从中获取项目。在您的情况下,它将是(不使用 2 for 循环):
# .yuRUbf -> container
for result in soup.select('.yuRUbf'):
# .DKV0Md -> CSS selector for title which is located inside a container
title = result.select_one('.DKV0Md').text
# grab <a> and extract href attribute.
# .get('href') equal to ['href']
link = result.select_one('a')['href']
完整代码和example in the online IDE:
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582'
}
response = requests.get('https://www.google.com/search?q=beautiful+soup', headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# enumerate() -> adds a counter to an iterable and returns it
# https://www.programiz.com/python-programming/methods/built-in/enumerate
for index, result in enumerate(soup.select('.yuRUbf')):
position = index + 1
title = result.select_one('.DKV0Md').text
link = result.select_one('a')['href']
print(position, title, link, sep='\n')
# part of the output
'''
1
Beautiful Soup 4.9.0 documentation - Crummy
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
2
Beautiful Soup Documentation — Beautiful Soup 4.4.0 ...
https://beautiful-soup-4.readthedocs.io/
3
BeautifulSoup4 - PyPI
https://pypi.org/project/beautifulsoup4/
'''
或者,您可以使用来自 SerpApi 的 Google Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。
您的案例的不同之处在于它是为此类任务创建的。您不必弄清楚要使用哪个 CSS 选择器、如何绕过来自 Google 或其他搜索引擎的阻止、随着时间的推移维护代码(如果 HTML 中的某些内容将被更改)。相反,请专注于您想要获取的数据。查看playground(需要登录)。
要集成的代码:
import os
from serpapi import GoogleSearch
params = {
"api_key": os.getenv("API_KEY"), # YOUR API KEY
"engine": "google", # search engine
"q": "Beautiful Soup", # query
"hl": "en" # language
# other parameters
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results["organic_results"]:
position = result["position"] # website rank position
title = result["title"]
link = result["link"]
print(position, title, link, sep="\n")
# part of the output
'''
1
Beautiful Soup 4.9.0 documentation - Crummy
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
2
Beautiful Soup Documentation — Beautiful Soup 4.4.0 ...
https://beautiful-soup-4.readthedocs.io/
3
BeautifulSoup4 - PyPI
https://pypi.org/project/beautifulsoup4/
'''
免责声明,我为 SerpApi 工作。
附:我有一个dedicated web scraping blog。