[英]Google search scraper , Python
我是 Python 的新手,并试图制作一个 Google 搜索刮刀以获取股票价格,但我在下面运行我的代码我没有得到任何结果,而是获得了页面 HTML 格式。
import urllib.request
from bs4 import BeautifulSoup
import requests
url = 'https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=uwti'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
print(soup.prettify())
我是否遗漏了一些非常简单的东西,请给我一些提示。 我正在尝试提取当前的股票价值。如何在附加图像中提取此价值?
当您右键单击并在浏览器中选择查看源代码时,它就在源代码中。 您只需要稍微更改url并传递一个用户代理以匹配您使用请求在那里看到的内容:
In [2]: from bs4 import BeautifulSoup
...: import requests
...:
...: url = 'https://www.google.com/search?q=uwti&rct=j'
...: response = requests.get(url, headers={
...: "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (K
...: HTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"})
...: html = response.content
...:
...: soup = BeautifulSoup(html, "html.parser")
...: print(soup.select_one("span._Rnb.fmob_pr.fac-l").text)
...:
27.51
soup.find("span", class_="_Rnb fmob_pr fac-l").text
也可以工作,并且是使用带有 find 或find_all的css 类查找标签的正确方法
当您使用https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=uwti 时,您可以在 chrome 中看到,重定向到https://www.google .com/search?q=uwti&rct=j :
很容易做到:
user-agent
添加到您的请求中,以便 Google 将您的请求视为真正的用户访问。 用户代理 列表。CSS
选择器css
选择器与.select_one()
bs4
方法结合使用来获取数据。from bs4 import BeautifulSoup
import requests, lxml
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"
}
html = requests.get('https://www.google.com/search?q=spgsclp', headers=headers)
soup = BeautifulSoup(html.text, 'lxml')
current_stock_price = soup.select_one('.wT3VGc').text
print(current_stock_price)
>>> 108,52
或者,您可以使用来自 SerpApi 的Google Direct Answer Box API执行相同的操作。 这是一个付费 API,可免费试用 5,000 次搜索。
这个例子中最大的不同是你不必弄清楚为什么有些东西不起作用,也不必弄清楚如何抓取这些数据。 获取数据的过程要清晰得多。
集成代码:
from serpapi import GoogleSearch
params = {
"api_key": "YOUR_API_KEY",
"engine": "google",
"q": "spgsclp",
}
search = GoogleSearch(params)
results = search.get_dict()
current_stock_price = results['answer_box']['price']
print(current_stock_price)
>>> 108,52
免责声明,我为 SerpApi 工作。
查看Beautiful Soup's
文档,了解如何选择您刚刚解析的 HTML 文档的元素,您可以尝试以下操作:
soup.findAll("span", ['_Rnb', 'fmob_pr, 'fac-l'])
上述方法将找到实现列表中的类的 span 元素。
仅供参考:我所看到的初始请求不会获取股票价格,使用浏览器的Inspect Element
功能来捕获发送的请求,据我所见,有一个对 url https://www.google.gr/async/finance_price_updates
的请求https://www.google.gr/async/finance_price_updates
。 也许这用于获取股票的价格,看看您是否可以直接向它发送请求而不是获取整个 HTML。
谷歌不会给你刮它所以你必须使用一些 API 或只是改变股票的网站。
import urllib
from bs4 import BeautifulSoup
url = 'siteurl'
response = urllib.urlopen(url)
soup = BeautifulSoup(response, "html.parser")
print(soup.findAll("div", { "class" : 'classname' }))
您可以通过更改“siteurl”和“classname”(您必须刮擦)来使用此代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.