您有 2 个选项。自行构建或使用 SERP API。
SERP API 会将 Google 搜索结果作为格式化的 JSON 响应返回。
我会推荐 SERP API,因为它更易于使用,而且您不必担心会被 Google 屏蔽。
1. SERP API
我对@987654321@ 有很好的体验。
您可以使用以下代码调用 API。确保将 YOUR_API_TOKEN 替换为您的 scraperbox API 令牌。
import urllib.parse
import urllib.request
import ssl
import json
ssl._create_default_https_context = ssl._create_unverified_context
# Urlencode the query string
q = urllib.parse.quote_plus("Where can I get the best coffee")
# Create the query URL.
query = "https://api.scraperbox.com/google"
query += "?token=%s" % "YOUR_API_TOKEN"
query += "&q=%s" % q
query += "&proxy_location=gb"
# Call the API.
request = urllib.request.Request(query)
raw_response = urllib.request.urlopen(request).read()
raw_json = raw_response.decode("utf-8")
response = json.loads(raw_json)
# Print the first result title
print(response["organic_results"][0]["title"])
2。构建自己的 Python 爬虫
我最近在how to scrape search results with Python 上写了一篇深度博文。
这里是一个简短的总结。
首先您应该获取 Google 搜索结果页面的 HTML 内容。
import urllib.request
url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'
# Perform the request
request = urllib.request.Request(url)
# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()
# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
然后您可以使用BeautifulSoup 提取搜索结果。
例如,下面的代码将获取所有标题。
from bs4 import BeautifulSoup
# The code to get the html contents here.
soup = BeautifulSoup(html, 'html.parser')
# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
# Search for a h3 tag
results = div.select("h3")
# Check if we have found a result
if (len(results) >= 1):
# Print the title
h3 = results[0]
print(h3.get_text())
您可以扩展此代码以提取搜索结果 url 和描述。