【问题标题】:how to web scrape a google results?如何网络抓取谷歌结果?
【发布时间】:2021-01-18 23:05:49
【问题描述】:

我需要获取 google 结果页面的内容,如下所示:

我尝试使用此代码使用 xpath,但没有找到该元素

import lxml.html
import requests

html= requests.get("https://www.google.com/search?q=curitiba")
lxml = lxml.html.fromstring(html.content)




test=lxml.xpath('/html/body/div[7]/div[2]/div[9]/div[3]/div/div/div[1]/div[2]/div/div/div/div[1]/div/div/div/div[1]/div/div/div/div/span/text()')

print(test)

这是chrome本身提供的xpath

我怎样才能得到这个页面的内容?

【问题讨论】:

    标签: python web screen-scraping


    【解决方案1】:

    使用BeautifulSoup:

    import bs4
    import requests
    html = requests.get("https://www.google.com/search?q=curitiba")
    soup = bs4.BeautifulSoup(html.content)
    
    targeth3 = soup.find("h3", string="Descrição")  # Finds the h3 tag above the span
    targetspantext = targeth3.nextSibling.text  # access the text in the target span tag
    

    编辑:您无法通过请求检索该框,因为它已加载 javascript。您可以使用 selenium 或使用 https://serpapi.com/。您可以使用 API 检索该框,它称为“知识图”

    【讨论】:

    • 我之前尝试过使用它,但它不起作用,现在当我输入相同的代码时,它给出了一个错误:NoneType' object has no attribute 'nextSibling
    • 兄弟,这个 serpapi 正是我需要的,非常感谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多