【问题标题】:Empty list while scraping Google Search Result抓取 Google 搜索结果时清空列表
【发布时间】:2020-06-21 04:58:37
【问题描述】:

我正在尝试抓取 Google 搜索结果,但作为输出得到的只是空列表。你知道这里有什么问题吗?我在 Stack Overflow 上找到了类似的帖子,solution 说你应该尝试放置 user_agent。我试过了,但它仍然没有返回任何东西。如果您有任何想法,请分享。

import requests, webbrowser
from bs4 import BeautifulSoup

user_input = input("Enter something to search:")
print("googling.....")

google_search = requests.get("https://www.google.com/search?q="+user_input)
# print(google_search.text)

soup = BeautifulSoup(google_search.text , 'html.parser')
# print(soup.prettify())

search_results = soup.select('.r a')
# print(search_results)

for link in search_results[:5]:
    actual_link = link.get('href')
    print(actual_link)
    webbrowser.open('https://google.com/'+actual_link)

【问题讨论】:

    标签: python beautifulsoup scrape


    【解决方案1】:

    Google 阻止您的请求并抛出此错误当 Google 自动检测到来自您的计算机网络的请求似乎违反了 Terms of Service 时,就会显示此页面。该块将在这些请求停止后不久到期。同时,解决上述验证码将让您继续使用我们的服务。

    此流量可能是由恶意软件、浏览器插件或发送自动请求的脚本发送的。如果您共享网络连接,请向您的管理员寻求帮助 - 使用相同 IP 地址的不同计算机可能会负责。 Learn more

    如果您使用机器人已知使用的高级术语,或者非常快速地发送请求,有时可能会要求您解决 CAPTCHA。

    尝试使用 selenium + python 获取所有链接

    【讨论】:

      【解决方案2】:

      要从 Google 页面获取结果,您必须指定 User-Agent http 标头。对于英文结果,在搜索 URL 中添加 hl=en 参数:

      import requests
      from bs4 import BeautifulSoup
      
      
      headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}
      
      user_input = input("Enter something to search: ")
      print("googling.....")
      
      google_search = requests.get("https://www.google.com/search?hl=en&q="+user_input, headers=headers)  # <-- add headers and hl=en parameter
      
      soup = BeautifulSoup(google_search.text , 'html.parser')
      
      search_results = soup.select('.r a')
      
      for link in search_results:
          actual_link = link.get('href')
          print(actual_link)
      

      打印:

      Enter something to search: tree
      googling.....
      https://en.wikipedia.org/wiki/Tree
      #
      https://webcache.googleusercontent.com/search?q=cache:wHCoEH9G9w8J:https://en.wikipedia.org/wiki/Tree+&cd=22&hl=en&ct=clnk&gl=sk
      /search?hl=en&q=related:https://en.wikipedia.org/wiki/Tree+tree&tbo=1&sa=X&ved=2ahUKEwjmroPTuZLqAhVWWs0KHV4oCtsQHzAVegQIAxAH
      https://simple.wikipedia.org/wiki/Tree
      #
      https://webcache.googleusercontent.com/search?q=cache:tNzOpY417g8J:https://simple.wikipedia.org/wiki/Tree+&cd=23&hl=en&ct=clnk&gl=sk
      /search?hl=en&q=related:https://simple.wikipedia.org/wiki/Tree+tree&tbo=1&sa=X&ved=2ahUKEwjmroPTuZLqAhVWWs0KHV4oCtsQHzAWegQIARAH
      https://www.britannica.com/plant/tree
      #
      https://webcache.googleusercontent.com/search?q=cache:91hg5d2649QJ:https://www.britannica.com/plant/tree+&cd=24&hl=en&ct=clnk&gl=sk
      /search?hl=en&q=related:https://www.britannica.com/plant/tree+tree&tbo=1&sa=X&ved=2ahUKEwjmroPTuZLqAhVWWs0KHV4oCtsQHzAXegQIAhAJ
      https://www.knowablemagazine.org/article/living-world/2018/what-makes-tree-tree
      #
      https://webcache.googleusercontent.com/search?q=cache:AVSszZLtPiQJ:https://www.knowablemagazine.org/article/living-world/2018/what-makes-tree-tree+&cd=25&hl=en&ct=clnk&gl=sk
      https://teamtrees.org/
      #
      https://webcache.googleusercontent.com/search?q=cache:gVbpYoK7meUJ:https://teamtrees.org/+&cd=26&hl=en&ct=clnk&gl=sk
      https://www.ldoceonline.com/dictionary/tree
      #
      https://webcache.googleusercontent.com/search?q=cache:oyS4e3WdMX8J:https://www.ldoceonline.com/dictionary/tree+&cd=27&hl=en&ct=clnk&gl=sk
      https://en.wiktionary.org/wiki/tree
      #
      https://webcache.googleusercontent.com/search?q=cache:s_tZIjpvHZIJ:https://en.wiktionary.org/wiki/tree+&cd=28&hl=en&ct=clnk&gl=sk
      /search?hl=en&q=related:https://en.wiktionary.org/wiki/tree+tree&tbo=1&sa=X&ved=2ahUKEwjmroPTuZLqAhVWWs0KHV4oCtsQHzAbegQICBAH
      https://www.dictionary.com/browse/tree
      #
      https://webcache.googleusercontent.com/search?q=cache:EhFIP6m4MuIJ:https://www.dictionary.com/browse/tree+&cd=29&hl=en&ct=clnk&gl=sk
      https://www.treepeople.org/tree-benefits
      #
      https://webcache.googleusercontent.com/search?q=cache:4wLYFp4zTuUJ:https://www.treepeople.org/tree-benefits+&cd=30&hl=en&ct=clnk&gl=sk
      

      编辑:要过滤结果,您可以使用:

      import requests
      from bs4 import BeautifulSoup
      
      
      headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0'}
      
      user_input = input("Enter something to search: ")
      print("googling.....")
      
      google_search = requests.get("https://www.google.com/search?hl=en&q="+user_input, headers=headers)  # <-- add headers and hl=en parameter
      
      soup = BeautifulSoup(google_search.text , 'html.parser')
      
      search_results = soup.select('.r a')
      
      for link in search_results:
          actual_link = link.get('href')
          if actual_link.startswith('#') or \
             actual_link.startswith('https://webcache.googleusercontent.com') or \
             actual_link.startswith('/search?'):
              continue
          print(actual_link)
      

      打印(例如):

      Enter something to search: tree
      googling.....
      https://en.wikipedia.org/wiki/Tree
      https://simple.wikipedia.org/wiki/Tree
      https://www.britannica.com/plant/tree
      https://www.knowablemagazine.org/article/living-world/2018/what-makes-tree-tree
      https://teamtrees.org/
      https://www.ldoceonline.com/dictionary/tree
      https://en.wiktionary.org/wiki/tree
      https://www.dictionary.com/browse/tree
      https://www.treepeople.org/tree-benefits
      

      【讨论】:

      • 我找到了我出错的地方......这是调用标题的地方......谢谢。但是这里我们得到了两种类型的链接……难道不能只得到下面的一种链接吗?例如:不是webcache.googleusercontent.com/… /search?hl=en&q=related:en.wikipedia.org/wiki/… 而是仅simple.wikipedia.org/wiki/Tree??
      • 哦..Tysm...不是出于好奇而问的问题您在抓取谷歌搜索结果时从不使用 Recaptcha 或 429 之类的错误吗??
      • @BidhyaPokharel 从来没有,但我还不需要它。我可以想象谷歌有一些保护措施来防止大量废弃搜索结果。
      • 真幸运...对我来说即使我运行上述代码超过 2-3 次...由于 429 错误,我得到 [ ] 空列表。
      • @BidhyaPokharel 你做了什么来解决的?您刚刚添加了标题行?我正在调用标头,但它仍然返回一个空列表。
      【解决方案3】:

      如今,大多数网站都使用 JavaScript 来动态加载其网页。谷歌就是这些网站之一。为了加载完整的 DOM(文档对象模型),您需要一个 Javascript 引擎,而 beautifulsoup 和 requests 没有。 Arun 推荐了 selenium,我也这样做了,因为它有一个嵌入式 Javascript 引擎。

      这是 Python Selenium 文档: https://selenium-python.readthedocs.io/

      【讨论】:

        【解决方案4】:

        正如Serket 提到的那样,OP 所需的输出并非来自 JavaScript。 OP 需要的所有数据都位于 HTML 中。

        selenium 也没有任何意义,出于同样的原因,它都在 HTML 中,不是通过 JavaScript 呈现的。


        其他人提到的问题之一是因为没有指定user-agent,并且您可能传递了错误user-agent,这导致了完全不同的HTML包含错误消息或类似内容。 Check out what is your user-agent.

        通过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(YOUR_URL, headers=headers)
        

        您还可以通过在方括号中传递属性来获取属性:

        element.get('href')
        # is equivalent to
        element['href']
        

        代码和example in the online IDECSS 选择器reference):

        from bs4 import BeautifulSoup
        import requests
        
        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": "fus ro dah" # query
        }
        
        html = requests.get('https://www.google.com/search', headers=headers, params=params)
        soup = BeautifulSoup(html.text, 'lxml')
        
        # container with links and iterate over it
        for result in soup.select('.tF2Cxc'):
          link = result.select_one('.yuRUbf a')['href']
        
        -------
        '''
        https://elderscrolls.fandom.com/wiki/Unrelenting_Force_(Skyrim)
        https://knowyourmeme.com/memes/fus-ro-dah
        https://en.uesp.net/wiki/Skyrim:Unrelenting_Force
        https://www.urbandictionary.com/define.php?term=Fus%20ro%20dah
        https://www.etsy.com/market/fus_ro_dah
        https://www.nexusmods.com/skyrimspecialedition/mods/4889/
        https://www.textualtees.com/products/fus-ro-dah-t-shirt
        '''
        

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

        您的情况的不同之处在于您不需要弄清楚为什么或如何处理这样的问题,因为这部分(提取/抓取)已经为最终用户完成.需要做的只是迭代结构化 JSON 并得到你想要的。

        代码:

        import os
        from serpapi import GoogleSearch
        
        params = {
            "engine": "google",
            "q": "fus ro day",
            "api_key": os.getenv("API_KEY"),
        }
        
        search = GoogleSearch(params)
        results = search.get_dict()
        
        for result in results["organic_results"]:
          print(result['link'])
        
        ---------
        '''
        https://elderscrolls.fandom.com/wiki/Unrelenting_Force_(Skyrim)
        https://knowyourmeme.com/memes/fus-ro-dah
        https://en.uesp.net/wiki/Skyrim:Unrelenting_Force
        https://www.etsy.com/market/fus_ro_dah
        https://www.urbandictionary.com/define.php?term=Fus%20ro%20dah
        https://www.textualtees.com/products/fus-ro-dah-t-shirt
        https://tenor.com/search/fus-ro-dah-gifs
        '''
        

        P.S - 我有一篇博文更深入地介绍了如何抓取 Google Organic Search Results

        免责声明,我为 SerpApi 工作。

        【讨论】:

          猜你喜欢
          • 2015-11-23
          • 1970-01-01
          • 2010-12-05
          • 1970-01-01
          • 1970-01-01
          • 2011-12-06
          • 1970-01-01
          • 1970-01-01
          • 2023-01-17
          相关资源
          最近更新 更多