[英]Google Search Web Scraping with Python
最近學習了很多 python 來做一些工作中的項目。
目前我需要用谷歌搜索結果做一些 web 抓取。 我找到了幾個演示如何使用 ajax google api 進行搜索的網站,但是在嘗試使用它之后,它似乎不再受支持。 有什么建議么?
我一直在尋找一種方法,但似乎找不到目前有效的任何解決方案。
您可以隨時直接抓取 Google 結果。 為此,您可以使用 URL https://google.com/search?q=<Query>
這將返回前 10 個搜索結果。
然后你可以使用lxml來解析頁面。 根據您使用的內容,您可以通過 CSS-Selector ( .ra
) 或使用 XPath-Selector ( //h3[@class="r"]/a
) 查詢結果節點樹
在某些情況下,生成的 URL 會重定向到 Google。 通常它包含一個查詢參數q
,它將包含實際的請求 URL。
使用 lxml 和請求的示例代碼:
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from requests import get
raw = get("https://www.google.com/search?q=StackOverflow").text
page = fromstring(raw)
for result in page.cssselect(".r a"):
url = result.get("href")
if url.startswith("/url?"):
url = parse_qs(urlparse(url).query)['q']
print(url[0])
關於谷歌禁止您的 IP 的說明:根據我的經驗,只有當您開始向谷歌發送搜索請求時,谷歌才會禁止。 如果 Google 認為您是機器人,它將以 503 響應。
這是另一種可用於抓取 SERP 的服務 ( https://zenserp.com ) 它不需要客戶端並且更便宜。
這是一個python代碼示例:
import requests
headers = {
'apikey': '',
}
params = (
('q', 'Pied Piper'),
('location', 'United States'),
('search_engine', 'google.com'),
('language', 'English'),
)
response = requests.get('https://app.zenserp.com/api/search', headers=headers, params=params)
您有 2 個選擇。 自己構建或使用 SERP API。
SERP API 會將 Google 搜索結果作為格式化的 JSON 響應返回。
我會推薦 SERP API,因為它更易於使用,而且您不必擔心被 Google 屏蔽。
1. SERP API
我對scraperbox serp api有很好的經驗。
您可以使用以下代碼調用 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 爬蟲
我最近寫了一篇關於如何使用 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 和描述。
你也可以使用像Serp API這樣的第三方服務——我編寫並運行了這個工具——這是一個付費的谷歌搜索引擎結果 API。 解決了被屏蔽的問題,不用租代理自己解析結果。
與 Python 集成很容易:
from lib.google_search_results import GoogleSearchResults
params = {
"q" : "Coffee",
"location" : "Austin, Texas, United States",
"hl" : "en",
"gl" : "us",
"google_domain" : "google.com",
"api_key" : "demo",
}
query = GoogleSearchResults(params)
dictionary_results = query.get_dictionary()
GitHub: https://github.com/serpapi/google-search-results-python
當前的答案將起作用,但谷歌將禁止您進行報廢。
我當前的解決方案使用requests_ip_rotator
import requests
from requests_ip_rotator import ApiGateway
import os
keywords = ['test']
def parse(keyword, session):
url = f"https://www.google.com/search?q={keyword}"
response = session.get(url)
print(response)
if __name__ == '__main__':
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
gateway = ApiGateway("https://www.google.com", access_key_id=AWS_ACCESS_KEY_ID,
access_key_secret=AWS_SECRET_ACCESS_KEY)
gateway.start()
session = requests.Session()
session.mount("https://www.google.com", gateway)
for keyword in keywords:
parse(keyword, session)
gateway.shutdown()
您可以在 AWS 控制台中創建 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY。
這個方案可以讓你解析100萬個請求(亞馬遜免費限制)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.