如何通过网络抓取谷歌搜索结果?

时间:2021-01-18 23:05:49

标签: python web screen-scraping

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

enter image description here

enter image description here

我尝试使用此代码使用 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

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

1 个答案:

答案 0 :(得分:0)

使用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。您可以使用硒或使用 https://serpapi.com/。您可以使用 API 检索该框,它称为“知识图”