首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么雅虎财务数据只在我抓取时使用header时更新?

为什么雅虎财务数据只在我抓取时使用header时更新?
EN

Stack Overflow用户
提问于 2021-09-10 14:41:10
回答 1查看 142关注 0票数 0

因此,我最近学习了BeautifulSoup,并决定从雅虎财经上搜集股票数据作为练习。

这里的代码只返回股票的静态价格,没有更新

代码语言:javascript
复制
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“参数,并且它起作用了。

代码语言:javascript
复制
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())

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-11 05:44:51

HTTP标头允许客户端和服务器通过HTTP请求或响应传递附加信息。

代码语言:javascript
复制
 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69133943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档