【问题标题】:Scraping and parsing Google search results using Python使用 Python 抓取和解析 Google 搜索结果
【发布时间】:2011-12-06 12:07:31
【问题描述】:

我向question 询问了关于实现抓取和保存网页的总体思路。 原问题的一部分是:如何从互联网上抓取并保存大量的“关于”页面。

经过一些进一步的研究,我在抓取和解析方面有了一些选择(列在底部)。

今天,我遇到了另一个Ruby discussion,关于如何从 Google 搜索结果中抓取。这为我的问题提供了一个很好的替代方案,可以节省爬行部分的所有工作。

新的问题是:在 Python 中,抓取给定关键字的 Google 搜索结果,在本例中为“About”,最后获取链接以进行进一步解析. 继续使用的方法和库的最佳选择是什么? (以易于学习和易于实施为衡量标准)。

附言在this website,实现了完全相同的东西,但关闭并要钱以获得更多结果。如果没有可用的开源代码,我宁愿自己做,同时学习更多 Python。

哦,顺便说一句,如果有的话,从搜索结果中解析链接的建议会很好。尽管如此,易于学习和易于实施。刚开始学习Python。 :P


最终更新,问题已解决。使用 xgoogle 的代码,请阅读以下部分中的注释以使 xgoogle 正常工作。

import time, random
from xgoogle.search import GoogleSearch, SearchError

f = open('a.txt','wb')

for i in range(0,2):
    wt = random.uniform(2, 5)
    gs = GoogleSearch("about")
    gs.results_per_page = 10
    gs.page = i
    results = gs.get_results()
    #Try not to annnoy Google, with a random short wait
    time.sleep(wt)
    print 'This is the %dth iteration and waited %f seconds' % (i, wt)
    for res in results:
        f.write(res.url.encode("utf8"))
        f.write("\n")

print "Done"
f.close()

Note 关于 xgoogle(下面由 Mike Pennington 回答): 它的 Github 的最新版本默认情况下已经无法使用,可能是由于 Google 搜索结果的变化。该工具主页上的这两个回复(ab)提供了一个解决方案,目前仍在使用此调整。但也许有一天它可能会由于 Google 的更改/阻止而再次停止工作。


目前已知的资源:

    1234563 Mechanize 在不同的讨论中也被多次提及。
  • 对于解析 HTML,BeautifulSoup 似乎是最 流行的选择。当然。 lxml 也是。

【问题讨论】:

  • 你在正确的轨道上,但如果你过于激进,如果谷歌阻止你或开始抛出验证码,请不要感到惊讶。
  • @jathanism 哦..是的..对..我已经考虑过了。谢谢你的提示。希望我能在被 Google 发现之前得到我的结果。
  • 你为什么不用谷歌的实际search API
  • @DanielRoseman,很好。现在去看看。
  • 它仅从 2 页打印结果,而 google 上的搜索结果显示超过数千。无论如何我可以将所有网址抓取到最后吗?

标签: python screen-scraping web-scraping google-search-api


【解决方案1】:

您可能会发现xgoogle 很有用...您所要求的大部分内容都在那里...

【讨论】:

  • 查看了一下,似乎正是我要找的东西。这是“google scrape python”在谷歌中的第一个热门。只搜索了stackoverflow和pypi....
【解决方案2】:

有一个twill 用于模拟浏览器的库。我在需要使用谷歌电子邮件帐户登录时使用它。虽然它是一个很棒的工具,但它已经很老了,而且现在似乎缺乏支持(最新版本于 2007 年发布)。 如果您要检索需要 cookie 处理或身份验证的结果,它可能会很有用。 twill 可能是为此目的的最佳选择之一。 顺便说一句,它基于mechanize

至于解析,你是对的,BeautifulSoupScrapy 很棒。 BeautifulSoup 背后的一件很酷的事情是它可以处理无效的 HTML(例如,与 Genshi 不同。)

【讨论】:

    【解决方案3】:

    看看这个很棒的用于网络抓取的 urllib 包装器https://github.com/mattseh/python-web/blob/master/web.py

    【讨论】:

      【解决方案4】:

      另一个使用 Python 抓取 Google 搜索结果的选项是 ZenSERP

      我喜欢易于使用的 API 优先方法,并且 JSON 结果很容易集成到我们的解决方案中。

      以下是curl 请求的示例:

      curl "https://app.zenserp.com/api/search" -F "q=Pied Piper" -F "location=United States" -F "search_engine=google.com" -F "language=English" -H "apikey: APIKEY"
      

      然后回应:

      {
        "q": "Pied Piper",
        "domain": "google.com",
        "location": "United States",
        "language": "English",
        "url": "https://www.google.com/search?q=Pied%20Piper&num=100&hl=en&gl=US&gws_rd=cr&ie=UTF-8&oe=UTF-8&uule=w+CAIQIFISCQs2MuSEtepUEUK33kOSuTsc",
        "total_results": 17100000,
        "auto_correct": "",
        "auto_correct_type": "",
        "results": []
      }
      

      以 Python 代码为例:

      import requests
      
      headers = {
          'apikey': 'APIKEY',
      }
      
      params = (
          ('q', 'Pied Piper'),
          ('location', 'United States'),
          ('search_engine', 'google.com'),
          ('language', 'English'),
      )
      
      response = requests.get('https://app.zenserp.com/api/search', headers=headers, params=params)
      

      【讨论】:

      • 付费仅限有限免费访问
      【解决方案5】:

      要从 Google 搜索结果的多个页面中提取链接,您可以使用 SerpApi。这是一个免费试用的付费 API。

      Full example

      import os
      
      # Python package: https://pypi.org/project/google-search-results
      from serpapi import GoogleSearch
      
      params = {
          "engine": "google",
          "q": "about",
          "api_key": os.getenv("API_KEY"),
      }
      
      search = GoogleSearch(params)
      
      pages = search.pagination()
      
      for result in pages:
          print(f"Current page: {result['serpapi_pagination']['current']}\n")
      
          for organic_result in result["organic_results"]:
              print(
                  f"Title: {organic_result['title']}\nLink: {organic_result['link']}\n"
              )
      

      输出

      Current page: 12
      URL: https://fi.google.com/
      URL: https://www.mayoclinic.org/about-mayo-clinic
      
      ...
      
      Current page: 18
      URL: https://igem.org/About
      URL: https://www.ieee.org/
      URL: https://www.cancer.org/
      
      ...
      

      免责声明:我在 SerpApi 工作。

      【讨论】:

        【解决方案6】:

        这一刻很适合。如果进行任何搜索,抓取工具会继续抓取标题及其链接,直到没有更多的下一页或您的 IP 地址被禁止为止。确保您的 bs4 版本 >= 4.7.0,因为我在脚本中使用了伪 CSS 选择器。

        from bs4 import BeautifulSoup
        from urllib.parse import urljoin
        import requests
        
        base = "https://www.google.de"
        link = "https://www.google.de/search?q={}"
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
        }
        
        def grab_content(link):
            res = requests.get(link,headers=headers)
            soup = BeautifulSoup(res.text,"lxml")
            for container in soup.select("[class='g'] a[href^='http'][data-ved]:has(h3)"):
                post_title = container.select_one("h3").get_text(strip=True)
                post_link = container.get('href')
                yield post_title,post_link
        
            next_page = soup.select_one("a[href][id='pnnext']")
            if next_page:
                next_page_link = urljoin(base,next_page.get("href"))
                yield from grab_content(next_page_link)
        
        if __name__ == '__main__':
            search_keyword = "python"
            qualified_link = link.format(search_keyword.replace(" ","+"))
            for item in grab_content(qualified_link):
                print(item)
        

        【讨论】:

          【解决方案7】:
          from urllib.request import urlopen
          from bs4 import BeautifulSoup
          import urllib.request
          import re
          
          import numpy as np
          count=0
          query=input("query>>")
          query=query.strip().split()
          query="+".join(query)
          
          html = "https://www.google.co.in/search?site=&source=hp&q="+query+"&gws_rd=ssl"
          req = urllib.request.Request(html, headers={'User-Agent': 'Mozilla/5.0'})
          
          soup = BeautifulSoup(urlopen(req).read(),"html.parser")
          
          #Regex
          reg=re.compile(".*&sa=")
          
          links = []
          #Parsing web urls
          for item in soup.find_all('h3', attrs={'class' : 'r'}):
              line = (reg.match(item.a['href'][7:]).group())
              links.append(line[:-4])
          
          print(links)
          

          这应该很方便....更多信息请访问 - https://github.com/goyal15rajat/Crawl-google-search.git

          【讨论】:

            【解决方案8】:

            这是一个 Python 脚本,它使用 requestsBeautifulSoup 来抓取 Google 搜索结果。

            import urllib
            import requests
            from bs4 import BeautifulSoup
            
            # desktop user-agent
            USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0"
            # mobile user-agent
            MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36"
            
            query = "hackernoon How To Scrape Google With Python"
            query = query.replace(' ', '+')
            URL = f"https://google.com/search?q={query}"
            
            headers = {"user-agent": USER_AGENT}
            resp = requests.get(URL, headers=headers)
            
            if resp.status_code == 200:
                soup = BeautifulSoup(resp.content, "html.parser")
                results = []
                for g in soup.find_all('div', class_='r'):
                    anchors = g.find_all('a')
                    if anchors:
                        link = anchors[0]['href']
                        title = g.find('h3').text
                        item = {
                            "title": title,
                            "link": link
                        }
                        results.append(item)
                print(results)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2010-12-05
              • 2015-11-23
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-11-03
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多