如何让此代码循环用于其他股票?例如,我希望它一次执行即可重复显示 Telsa、Amazon、Apple 等股票?
如何让此代码循环用于其他股票?例如,我希望它一次执行即可重复显示 Telsa、Amazon、Apple 等股票?在我的代码中,它只显示一只股票,我希望它显示多只股票。
代码: <代码>
import requests
from bs4 import BeautifulSoup
def create_url():
url = f'https://finance.yahoo.com/quote/TSLA'
return url
def get_html(url):
header = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}
response = requests.get(url, headers = header)
if response.status_code == 200:
return response.text
else:
return None
def parse_data(html):
soup = BeautifulSoup(html,'html.parser')
name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text
price = soup.select_one('#quote-header-info > div.My(6px).Pos(r).smartphone_Mt(6px).W(100%) > div.D(ib).Va(m).Maw(65%).Ov(h) > div.D(ib).Mend(20px) > fin-streamer.Fw(b).Fz(36px).Mb(-4px).D(ib)').text
stock_data = {
'name':name,
'price':price,
}
return stock_data
def main():
url = create_url()
# get html
html = get_html(url)
data = parse_data(html)
#return data
print(data)
if __name__ == '__main__':
main()
How do I get this code to loop for other stocks? For example, I want it to repeat and show stocks like Telsa, Amazon, Apple all in one executution? In my code, it only shows one stock and I want it to display multiple stocks.
Code:
import requests from bs4 import BeautifulSoup def create_url(): url = f'https://finance.yahoo.com/quote/TSLA' return url def get_html(url): header = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'} response = requests.get(url, headers = header) if response.status_code == 200: return response.text else: return None def parse_data(html): soup = BeautifulSoup(html,'html.parser') name = soup.find('h1', {'class': 'D(ib) Fz(18px)'}).text price = soup.select_one('#quote-header-info > div.My(6px).Pos(r).smartphone_Mt(6px).W(100%) > div.D(ib).Va(m).Maw(65%).Ov(h) > div.D(ib).Mend(20px) > fin-streamer.Fw(b).Fz(36px).Mb(-4px).D(ib)').text stock_data = { 'name':name, 'price':price, } return stock_data def main(): url = create_url() # get html html = get_html(url) data = parse_data(html) #return data print(data) if __name__ == '__main__': main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试更改您的
create_url
以采用一个参数,该参数将是您要查询的股票,如下所示:然后,您可以在主函数中创建一个股票代码列表,并为每个股票代码调用该函数。
Try changing your
create_url
to take one parameter, which will be the stock you want to query, like so:Then, you can create a list of tickers in your main function and call the function for each ticker.