【问题标题】:Get number of results on Google search results in Python 3在 Python 3 中获取 Google 搜索结果的结果数
【发布时间】:2016-05-08 07:28:04
【问题描述】:

有什么方法可以返回Python3中的谷歌搜索结果的数量吗?我从 SO 尝试了几种方法,但没有一个仍然有效:

>>> import requests
>>> from bs4 import BeautifulSoup

>>> def get_results(name):
        re = requests.get('https://www.google.com/search', params={'q':name})
        soup = BeautifulSoup(re.text, 'lxml')
        response = soup.find('div', {'id': 'resultStats'})
        return int(response.text.replace(',', '').split()[1])

>>> get_results('Leonardo DiCaprio')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in get_results
AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

  • 对我来说很好用,什么版本的 bs4?
  • 4.4.1 - 不知道谷歌搜索API是否限制搜索次数?
  • 他们几乎肯定会这样做,但它对你有用吗?
  • 是的,我之前搜索过 100 多个单词。但是有没有其他方法可以摆脱它?
  • 打印返回的 html 时看到了什么?

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


【解决方案1】:

您的get_results() 函数中的responseNone,因为对Google 的请求返回了错误页面,因此您要查找的div 不存在。在尝试解析结果之前,您应该检查成功的响应状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2017-10-14
    相关资源
    最近更新 更多