在Python 3中获取Google搜索结果的结果数量

时间:2016-05-07 10:56:49

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

有没有办法在Python3中返回Google搜索结果的数量?我尝试了几种方法,但它们都没有工作:

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

1 个答案:

答案 0 :(得分:0)

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

相关问题