确保您使用user-agent 来伪造真实的用户访问(请参阅代码中的headers)否则,Google 最终会阻止您的请求。
代码:
import requests, lxml
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"
}
params = {'q': 'facebook Sachs'}
html = requests.get(f'https://www.google.com/search',
headers=headers,
params=params).text
soup = BeautifulSoup(html, 'lxml')
# Container where needed data located
for container in soup.select('.tF2Cxc'):
# Grabbing link itself
link = container.a['href']
print(link)
输出:
https://www.facebook.com/SACHSofficial/
https://www.facebook.com/SachsPerformanceOfficial/
https://www.facebook.com/jeffrey.sachs
https://www.facebook.com/SachsArtsPhilly/
https://www.facebook.com/public/John-Sachs
https://m.facebook.com/SACHSofficial/photos/?ref=page_internal&mt_nav=0
https://www.facebook.com/SachsMedia/
https://www.facebook.com/goldmansachs/
https://www.facebook.com/teamsachs
https://www.facebook.com/SachsAssociates/
或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 来完成此操作。这是一个带有免费计划的付费 API。
要集成的代码:
from serpapi import GoogleSearch
params = {
"api_key": "YOUR_API_KEY",
"engine": "google",
"q": "facebook Sachs",
"google_domain": "google.com",
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results['organic_results']:
link = result['link']
print(link)
输出:
https://www.facebook.com/SACHSofficial/
https://www.facebook.com/SachsPerformanceOfficial/
https://www.facebook.com/jeffrey.sachs
https://www.facebook.com/public/John-Sachs
https://m.facebook.com/SACHSofficial/photos/?ref=page_internal&mt_nav=0
https://www.facebook.com/teamsachs
https://www.facebook.com/SachsMedia/
https://www.facebook.com/goldmansachs/
https://www.facebook.com/SachsArtsPhilly/
https://www.facebook.com/SachsAssociates/
免责声明,我为 SerpApi 工作。