代码之家  ›  专栏  ›  技术社区  ›  user4754843

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

  •  1
  • user4754843  · 技术社区  · 10 年前

    有没有办法在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'
    
    1 回复  |  直到 10 年前
        1
  •  0
  •   augurar    10 年前

    response 在您的 get_results() 函数是 None 因为对Google的请求返回了一个错误页面,所以您要查找的div不存在。在尝试分析结果之前,应该检查成功的响应状态。