【问题标题】:Python: parse links from Google with searchPython:使用搜索解析来自 Google 的链接
【发布时间】:2017-06-19 05:43:05
【问题描述】:

我需要在 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')

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

【问题讨论】:

  • 试试html = requests.get(url).text
  • @MithileshKumar 它没有帮助
  • 可以打印显示requests.get(url).text
  • @MithileshKumar 它以<!DOCTYPE doctype html> <html itemscope="" itemtype="http://schema.org/WebPage" lang="ru"><head><meta content="Поиск информации в интернете: веб страницы, картинки, видео и многое другое." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=utf-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script>(function(){window.google= 开头
  • 上面的“引用”是什么?

标签: python python-requests google-search


【解决方案1】:

为了获得您在浏览器中看到的实际响应,您需要发送额外的headers,更具体地说是user-agent(除了发送additional query parameters),这是充当“真实”用户所必需的当机器人或浏览器发送虚假的user-agent 字符串以宣布自己为不同的客户端时访问。

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

您可以在我写的关于 how to reduce the chance of being blocked while web scraping 的博文中了解更多信息。

通过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
'''

免责声明,我为 SerpApi 工作。

【讨论】:

    【解决方案2】:

    试试:

    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 得到的结果不完整,我不知道为什么

    【讨论】:

      【解决方案3】:

      用途:

      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')
      

      【讨论】:

        猜你喜欢
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-30
        • 2011-12-06
        • 1970-01-01
        • 2021-01-25
        • 1970-01-01
        相关资源
        最近更新 更多