【问题标题】:Python searching on Google在 Google 上搜索 Python
【发布时间】:2017-09-09 10:47:00
【问题描述】:

我想在 Google 上执行一些搜索,以阅读有关自定义搜索词的最新消息,我使用了一个简单的请求,使用 BeautifulSoup 来解析 html。

import requests
from bs4 import BeautifulSoup

response = requests.get("https://www.google.com/search?q=roger+federer&hl=en?cr=countryGB?as_qdr=y")
page = BeautifulSoup(response.content, "lxml")

特别是,我只想搜索英文新闻(GB 或 US 相同),但我也得到了意大利结果(我在意大利...)。

我该如何避免呢?

最终,是否有为此目的编写的包/API/工具? (我知道 Google 关闭了其官方 API)。

【问题讨论】:

  • 在查询字符串中将?替换为&
  • 试试这个网址news.google.com/news/search/section/q/roger+federer/…。你可以用任何东西代替roger+federer
  • 以这种方式修复:https://www.google.com/search?q=roger+federer&lr=lang_en&cr=countryGB&as_qdr=y ... ? 是问题所在。
  • 提交程序化搜索查询是违反谷歌的Webmaster Guidelinesterms of service的。对 Google 运行此代码可能会导致 Google 显示来自您 IP 地址的搜索的验证码。

标签: python-3.x python-requests google-search


【解决方案1】:

要获得美国或英国的结果,您可以使用 gl 查询参数,它代表 用于 Google 搜索的国家/地区

通过query params:

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

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

最终出现的下一个问题是您没有指定user-agent。您需要发送user-agent,这将作为“真正的”用户访问。当机器人或浏览器发送虚假的user-agent 字符串以宣布自己为不同的客户端时。因为default requests user-agent is python-requests

您可以在我写的关于 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)

代码和example in the 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',
  'gl': 'us',       # United States results
  'hl': 'en',
}

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

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

或者,您可以使用来自 SerpApi 的 Google Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。

您的情况的不同之处在于,此代码通常更易于阅读,如果 HTML 中的某些内容发生更改,则无需随着时间的推移对其进行维护(因为有专门的开发团队负责处理它 em>),找出如何绕过 Google 或其他搜索引擎的屏蔽。

要集成的代码:

import os
from serpapi import GoogleSearch

params = {
  "engine": "google",
  "q": "tesla",
  "hl": "en",
  "gl": "us",   # country to search from
  "api_key": os.getenv("API_KEY"),
}

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

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

免责声明,我为 SerpApi 工作。

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 2023-03-21
    • 2021-04-04
    相关资源
    最近更新 更多