Google搜索结果的获取通常涉及网络爬虫技术或使用官方API。由于Google有严格的反爬虫机制,直接爬取搜索结果页面可能会遇到技术挑战和法律问题。
这是Google提供的官方API,需要申请API密钥。
import requests
def google_search(api_key, search_engine_id, query, url_to_find=None):
base_url = "https://www.googleapis.com/customsearch/v1"
params = {
'key': api_key,
'cx': search_engine_id,
'q': query,
'num': 10 # 获取10条结果
}
response = requests.get(base_url, params=params)
results = response.json()
if url_to_find:
for i, item in enumerate(results.get('items', []), 1):
if url_to_find in item.get('link', ''):
return f"URL found at position {i}: {item['link']}"
return "URL not found in top results"
return results.get('items', [])
# 使用示例
api_key = "YOUR_API_KEY"
search_engine_id = "YOUR_SEARCH_ENGINE_ID"
results = google_search(api_key, search_engine_id, "Python programming")
print(results)
from googlesearch import search
def search_google(query, url_to_find=None, num_results=10):
results = []
for result in search(query, num_results=num_results):
results.append(result)
if url_to_find and url_to_find in result:
return f"URL found: {result}"
if url_to_find:
return "URL not found in top results"
return results
# 使用示例
results = search_google("Python web scraping", "https://example.com")
print(results)
原因: Google的反爬虫机制检测到自动化请求
解决方案:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
原因: 免费API有查询限制,或爬取被中断
解决方案:
原因: 网络延迟或请求过多
解决方案:
以上方法提供了获取Google搜索结果的基本框架,请根据实际需求和法律合规性选择合适的方法。
没有搜到相关的文章