因此,我最近学习了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())我的问题是,为什么雅虎财经上的抓取价格只会在包含“标题”的情况下更新?我不明白为什么它会这样。
发布于 2021-09-11 05:44:51
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'作为附加信息包含在标头中才能访问。
https://stackoverflow.com/questions/69133943
复制相似问题