【问题标题】:SERP Scraping with Beautiful Soup用美丽的汤刮 SERP
【发布时间】:2020-05-27 15:54:50
【问题描述】:

我正在尝试构建一个简单的脚本来抓取 Google 的第一个搜索结果页面并将结果导出为 .csv。 我设法获得了 URL 和标题,但我无法检索描述。 我一直在使用以下代码:

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 = "pizza recipe"
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
            desc = g.select('span')
            description = g.find('span',{'class':'st'}).text
            item = {
                "title": title,
                "link": link,
                "description": description
            }
            results.append(item)

import pandas as pd
df = pd.DataFrame(results)
df.to_excel("Export.xlsx")

我在运行代码时收到以下消息:

description = g.find('span',{'class':'st'}).text
AttributeError: 'NoneType' object has no attribute 'text'

基本上,该字段是空的。

有人可以帮我这条线,以便我可以从 sn-p 获取所有信息吗?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    它不在 div class="r" 内。它在 div class="s"

    所以改成这个来说明:

    description = g.find_next_sibling("div", class_='s').find('span',{'class':'st'}).text
    

    从当前元素,它会找到下一个 div,class="s"。然后就可以拉出<span>标签了

    【讨论】:

      【解决方案2】:

      尝试使用select_one() or select() bs4 方法。它们更灵活且易于阅读。 CSS 选择器reference.

      另外,你可以pass URL params 因为requests 为你做任何事情,就像这样:

      # instead of this:
      query = "pizza recipe"
      query = query.replace(' ', '+')
      URL = f"https://google.com/search?q={query}"
      
      # try to use this:
      params = {
        'q': 'fus ro dah', # query
        'hl': 'en'
      }
      
      requests.get('URL', params=params)
      

      如果你想写信给.csv,那么你需要使用.to_csv()而不是.to_excel()

      如果你想去掉pandas索引列,那么你可以通过index=False,例如df.to_csv('FILE_NAME', index=False)


      代码和example in the online IDE

      import pandas as pd
      import requests
      from bs4 import BeautifulSoup
      
      
      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
        'hl': 'en'
      }
      
      resp = requests.get("https://google.com/search", headers=headers, params=params)
      
      if resp.status_code == 200:
          soup = BeautifulSoup(resp.text, "html.parser")
      
          results = []
      
          for result in soup.select('.tF2Cxc'):
            title = result.select_one('.DKV0Md').text
            link = result.select_one('.yuRUbf a')['href']
            snippet = result.select_one('#rso .lyLwlc').text
      
            item = {
              "title": title,
              "link": link,
              "description": snippet
            }
      
            results.append(item)
      
      df = pd.DataFrame(results)
      df.to_csv("BS4_Export.csv", index=False)
      

      或者,您可以使用来自 SerpApi 的 Google Organic Results API 来做同样的事情。这是一个带有免费计划的付费 API。

      您的情况的不同之处在于,您不需要弄清楚要使用哪些选择器以及为什么它们不工作,尽管它们应该为最终用户完成。

      要集成的代码:

      from serpapi import GoogleSearch
      import os
      import pandas as pd
      
      params = {
        "api_key": os.getenv("API_KEY"),
        "engine": "google",
        "q": "fus ro dah",
        "hl": "en"
      }
      
      search = GoogleSearch(params)
      results = search.get_dict()
      
      data = []
      
      for result in results['organic_results']:
        title = result['title']
        link = result['link']
        snippet = result['snippet']
      
        data.append({
          "title": title,
          "link": link,
          "snippet": snippet
        })
      
      df = pd.DataFrame(results)
      df.to_csv("SerpApi_Export.csv", index=False)
      

      P.S - 我写了一篇关于如何抓取Google Organic Results 的更详细的博文。

      免责声明,我为 SerpApi 工作。

      【讨论】:

        猜你喜欢
        • 2021-01-15
        • 2014-05-28
        • 2020-12-13
        • 2019-03-13
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多