繁体   English   中英

为什么 web 通过漂亮的汤来刮股价,返回的价格与雅虎财经页面上的价格不同?

[英]Why is web scraping stock prices through beautiful soup returning a different price than the one on the Yahoo Finance page?

我正在尝试编写一个程序,它会给我一些不同股票的股价,但是当我运行我的程序时,它返回 116.71,而 Yahoo Finance 在页面上和 HTML 中将它作为 117.96(在写这个)。 知道发生了什么吗? 页面在这里 代码如下:

from bs4 import BeautifulSoup
import requests


url = 'https://finance.yahoo.com/quote/VTSAX?p=VTSAX&.tsrc=fin-srch'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text

print(price)

我认为雅虎会向您发送不同的数据,因为他们发现您的请求是自动的。

因此,您应该在标头中传递“真正的”用户代理:

from bs4 import BeautifulSoup
import requests


url = 'https://finance.yahoo.com/quote/VTSAX?p=VTSAX&.tsrc=fin-srch'
page = requests.get(url, headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
})
soup = BeautifulSoup(page.text, 'html.parser')
price = soup.find('fin-streamer', {'class': 'Fw(b) Fz(36px) Mb(-4px) D(ib)'}).text

print(price)

Output

117.96

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM