如何让Python爬虫脚本对多个ticker变量循环运行并按指定格式输出?
雅虎财经股票批量爬取脚本修改方案
修改后完整可运行代码
import requests from bs4 import BeautifulSoup # 模拟浏览器请求头,避免被雅虎反爬机制拦截 HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } # 批量股票代码列表,可自行增减,注意代码拼写正确(苹果官方代码为AAPL而非示例中的APPL) tickers = ['NFLX', 'AAPL', 'MSFT'] for ticker in tickers: try: url = f'https://finance.yahoo.com/quote/{ticker}' r = requests.get(url, headers=HEADERS, timeout=10) r.raise_for_status() soup = BeautifulSoup(r.text, 'html.parser') # 提前提取重复使用的页面节点,减少冗余代码 base_price_node = soup.find('div', {'class':'D(ib) Mend(20px)'}) market_cap_node = soup.find('div', {'class':'D(ib) W(1/2) Bxz(bb) Pstart(12px) Va(t) ie-7_D(i) ie-7_Pos(a) smartphone_D(b) smartphone_W(100%) smartphone_Pstart(0px) smartphone_BdB smartphone_Bdc($seperatorColor)'}) name = soup.find('div', {'class':'Mt(15px)'}).find_all('h1')[0].text price = base_price_node.find_all('span')[0].text change = base_price_node.find_all('span')[1].text cap_label = market_cap_node.find_all('span')[0].text cap_value = market_cap_node.find_all('span')[1].text top_news = soup.find('h3', {'class':'Mb(5px)'}).find_all('a')[0].text # 输出格式和原逻辑完全一致 print(name) print(url) print(f"Last Price: {price}") print(f"Change: {change}") print(f"{cap_label}: {cap_value}") print(f"Top News: {top_news}") # 不同股票结果用横线分隔,也可替换为print()实现空行分隔 print('-' * 60) except Exception as e: print(f"股票代码 {ticker} 爬取失败,请检查代码拼写或页面结构是否变化") print('-' * 60)
优化说明
- 支持批量爬取:将原单个股票代码改为列表格式,通过for循环遍历处理所有代码,符合需求
- 新增反爬适配:增加浏览器UA请求头、超时设置,避免雅虎财经直接拦截请求返回404
- 代码冗余精简:将重复调用的超长class选择器提前提取为节点变量,无需重复编写超长字符串,可读性和维护性更高
- 新增容错逻辑:加入try-except异常捕获,单只股票爬取失败不会导致整个脚本终止,会自动继续处理下一只股票
- 输出优化:每只股票的结果之间用横线分隔,也可自行替换为
print()实现空行分隔,和原有输出格式完全兼容
内容的提问来源于stack exchange,提问作者gambo
相关产品推荐
相关产品推荐

