为什么 yahoo finance 数据只在我使用 header 抓取时更新?

Why does yahoo finance data only update when I use header while scraping?

所以,我最近学习了 BeautifulSoup 并决定从雅虎财经抓取股票数据作为练习。

这里的代码只是returns股票的静态价格,不会更新

import requests
from bs4 import BeautifulSoup

def priceTracker():
    ticker = 'TSLA'
    url = f'https://finance.yahoo.com/quote/{ticker}?p={ticker}&.tsrc=fin-srch'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'lxml')
    price = soup.find_all('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
    return(price)

while True:
    print(priceTracker())

我在网上找到了一个解决方案,人们在第 8 行的 requests.get() 中包含了一个“header”参数,并且有效。

import requests
from bs4 import BeautifulSoup

def priceTracker():
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
    ticker = 'TSLA'
    url = f'https://finance.yahoo.com/quote/{ticker}?p={ticker}&.tsrc=fin-srch'
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'lxml')
    price = soup.find_all('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text
    return(price)

while True:
    print(priceTracker())

我的问题是,为什么 yahoo finance 上的抓取价格只在包含“header”时更新?我不明白为什么它会这样。

HTTP header让客户端和服务器通过 HTTP 请求或响应传递附加信息。

 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
    ticker = 'TSLA'
    url = f'https://finance.yahoo.com/quote/{ticker}?p={ticker}&.tsrc=fin-srch'
    response = requests.get(url, headers=headers)

有些网站需要 'User-Agent' 作为附加信息包含在 header 中才能访问。