为什么雅虎财务数据仅在我抓取时使用标题时更新?

问题描述 投票:0回答:2

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

此处的代码仅返回股票的静态价格,不会更新

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())

我的问题是,为什么雅虎财经上的刮取价格只有在包含“标题”时才会更新?我不明白为什么它会这样。

python-3.x beautifulsoup yahoo-finance
2个回答
0
投票

HTTP 标头允许客户端和服务器通过 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'
作为附加信息包含在标题中才能访问。


0
投票

我知道这不是你想要的,但非常感谢你让我知道这个标题,在我尝试这个之前,我的代码一直无法工作。我一直在到处寻找,直到找到这篇文章,我才感到非常难过。

© www.soinside.com 2019 - 2024. All rights reserved.