Python帮助获取特定值

2024-06-07 04:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

对python相当陌生。你知道吗

我想从你那里得到股票价格

url = "https://finance.yahoo.com/quote/" + readsymbollist[i]
sauce = urllib.request.urlopen(url).read()
soup = bs.BeautifulSoup(sauce,'lxml')

stockcompany = soup.find('h1', {'data-reactid': '7'}).text
#getcurrentprice = soup.find('span',{'data-reactid': '35'}).text

getcurrentprice = soup.find('span',{'class':'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})

这是一节课,但它什么也不回。你知道吗

此代码也用于处理数据-反应ID:35但是不再是了。为什么DataReactID7可以工作,但我在页面上看不到具体的跨度了。你知道吗

谢谢任何人


Tags: texthttpscomurldatafindyahoospan
3条回答

参见这些函数的文档。可能在最后一个函数中需要转义(“\”)特殊字符,如“,”等。你知道吗

您可能想看看pandas-datareader包,我使用过它,发现它非常有用。它很擅长从雅虎金融(Yahoo Finance)获取股价。你知道吗

根据您试图获取的元素,可能首先从查找最上面的标记开始,在本例中是'div',然后查找'span'标记,应该给出价格。你知道吗

# url = "https://finance.yahoo.com/quote/" + readsymbollist[i]
url = "https://finance.yahoo.com/quote/" + 'UA'  # example
sauce = urllib2.urlopen(url).read()
soup = bs4.BeautifulSoup(sauce,'lxml')

stockcompany = soup.find('h1', {'data-reactid': '7'}).text

# find the parent div
div = soup.find('div', {'class': 'Mt(6px) smartphone_Mt(15px)'}) 

结果:

print stockcompany           # UA - Under Armour, Inc.

# find the 'span' tag inside the div from previous step
print div.find('span').text  # 14.74

希望这有帮助。你知道吗

相关问题 更多 >