SERP用美丽的汤刮

时间:2020-05-27 15:54:50

标签: python web-scraping beautifulsoup

我正在尝试构建一个简单的脚本来抓取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'

基本上,该字段为空。

有人可以帮助我这一行,以便我从摘要中获取所有信息吗?

1 个答案:

答案 0 :(得分:0)

它不在div class =“ r”之内。在div class =“ s”

因此请更改为说明:

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

从当前元素中,它将找到具有class =“ s”的下一个div。然后,您可以拔出<span>标签