爬取股票数据通常涉及以下步骤:
选择数据源
使用股票交易所的API,如Nasdaq或NYSE。
利用第三方数据提供商,如Yahoo Finance或Alpha Vantage。
准备Python环境
安装Python和必要的库,如`requests`和`BeautifulSoup`。
建立网络请求
使用`requests`库向数据源发送HTTP请求。
指定URL、请求方法和请求头。
解析响应
使用`BeautifulSoup`解析HTML或JSON响应。
提取所需的股票信息,如股票名称、价格、成交量等。
存储或显示数据
将抓取到的数据存储在数据库、CSV文件或其他数据结构中。
可视化或显示数据,如打印或绘制图表。
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/58.0.3029.110 Safari/537.3'}
请求股票信息网页
url = 'http://quotes.money.163.com/old/query=hy010000&DataType=HS_RANK&sort=PERCENT&order=desc&count=24&page=0'
r = requests.get(url, headers=headers)
html = r.text
使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
提取股票代码
stock_codes = [re.findall(r'[sh]\d{6}', href) for href in [a['href'] for a in a if 'sh' in href]]
打印提取到的股票代码
for code in stock_codes:
print(code)
请注意,实际爬取时可能需要处理分页、异常情况、编码问题等。此外,确保遵守目标网站的使用条款和条件,以及相关的法律法规。