python - how to web scrape a google results?
问题描述
I need to get the contents of a google result page, like the following:
I tried to use xpath using this code, but did not find the element
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)
this is the xpath that chrome itself provides
how can i get the contents of this page?
解决方案
使用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 检索该框,它称为“知识图”
推荐阅读
- c# - 将客户端 Blazor 添加到现有的 Asp.Net Core 3.1 应用程序
- python - 根据多列中的值返回 pandas 中的行
- powershell - ForEach 内 PowerShell 中的格式表
- jquery - 表单内编码的引导模式 - 使用模型渲染,然后在表单外
- windows - Set-AuthenticodeSignature 不会执行 SHA256 时间戳?
- python - 用于计算期权价格的数组函数
- python - 矩形不会停止移动
- postgresql - 为我的 Postgres 对象编写基本测试代码
- python - 仅打印 2D 列表中的元素
- .net - 试图了解 RSACryptoServiceProvider 密钥和消息长度关系