为什么通过 beautiful soup 网络抓取股票价格返回的价格与雅虎财经页面上的价格不同?

1 python beautifulsoup web-scraping yahoo-finance

我正在尝试编写一个程序,该程序将为我提供一些不同股票的股价,但是当我运行我的程序时,它返回 116.71,而雅虎财经在页面和 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)
Run Code Online (Sandbox Code Playgroud)

Eug*_*nij 5

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

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

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)
Run Code Online (Sandbox Code Playgroud)

输出

117.96
Run Code Online (Sandbox Code Playgroud)