Python:通过搜索解析来自 Google 的链接

Python: parse links from Google with search

我需要在 Google 中搜索后解析带有结果的链接。 当我尝试查看页面代码和 Ctrl + U 时,我找不到带有链接的元素,这是我想要的。 但是当我看到元素代码时 Ctrl + Shift + I 我可以看到我应该解析什么元素来获取链接。 我使用代码

url = 'https://www.google.ru/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=' + str(query)
html = requests.get(url).content
soup = BeautifulSoup(html, 'html.parser')
links = soup.findAll('cite')

但它 returns 是空列表,因为没有这个元素。 我认为 html-code,returns requests.get(url).content 不完整,所以我无法获取这些元素。 我尝试使用 google.search 但它返回错误 it isn't used now. 有什么方法可以通过 google 中的搜索获取链接?

使用:

url = 'https://www.google.ru/search?q=name&rct=' + str(query)
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
links = soup.findAll('cite')

尝试:

url = 'https://www.google.ru/search?q=' + str(query)
html = requests.get(url)
soup = BeautifulSoup(html.text, 'lxml')
links = soup.findAll('cite')
print([link.text for link in links])

要安装lxml,请参阅http://lxml.de/installation.html

*注意:我选择 lxml 而不是 html.parser 的原因是有时我用 html.parser 得到的结果不完整,我不知道为什么

为了获得您在浏览器中看到的实际响应,您需要发送额外的 headers, more specifically user-agent (aside from sending additional query parameters),当漫游器或浏览器发送虚假响应时,它需要充当“真实”用户访问user-agent 声明自己为不同客户端的字符串。

这就是为什么您得到空输出的原因,因为您收到了具有不同元素(CSS 选择器、ID 等等)的不同 HTML。

您可以在我写的关于 how to reduce the chance of being blocked while web scraping 的博客 post 中阅读更多相关信息。

通过 user-agent:

headers = {
    'User-agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582'
}

requests.get('URL', headers=headers)

online IDE中的代码和示例:

from bs4 import BeautifulSoup
import requests, lxml

headers = {
    'User-agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582'
}

params = {
  'q': 'minecraft', # query
  'gl': 'us',       # country to search from
  'hl': 'en',       # language
}

html = requests.get('https://www.google.com/search', headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

for result in soup.select('.tF2Cxc'):
  link = result.select_one('.yuRUbf a')['href']
  print(link, sep='\n')

---------
'''
https://www.minecraft.net/en-us/
https://classic.minecraft.net/
https://play.google.com/store/apps/details?id=com.mojang.minecraftpe&hl=en_US&gl=US
https://en.wikipedia.org/wiki/Minecraft
'''

或者,您可以使用 SerpApi 中的 Google Organic API 来实现相同的目的。这是付费 API 和免费计划。

不同之处在于,您不必从头开始创建它,也不必在出现崩溃时随时间维护它。

要集成的代码:

import os
from serpapi import GoogleSearch

params = {
  "engine": "google",
  "q": "minecraft",
  "hl": "en",
  "gl": "us",
  "api_key": os.getenv("API_KEY"),
}

search = GoogleSearch(params)
results = search.get_dict()

for result in results["organic_results"]:
  print(result['link'])

-------
'''
https://www.minecraft.net/en-us/
https://classic.minecraft.net/
https://play.google.com/store/apps/details?id=com.mojang.minecraftpe&hl=en_US&gl=US
https://en.wikipedia.org/wiki/Minecraft
'''

Disclaimer, I work for SerpApi.