股票数据定向爬虫
目的:获取上交所和深交所所有股票的名称和交易信息
输出:保存到文件中
技术路线:requests-bs4-re
候选数据网站的选择
选取原则:股票信息静态存于HTML页面中,非js代码生成,没有Robots协议限制
选取方法:浏览器F12,源代码查看
数据网站的确定
获取股票列表
东方财富网:http://quote.eastmoney.com/stocklist.html
获取个股信息
百度股票:http://gupiao.baidu.com/stock/
单个股票:http://gupiao.baidu.com/stock/sz002439.html
原理分析
查看百度股票每只股票的网址:
https://gupiao.baidu.com/stock/sz300023.html
可以发现网址中有一个编号300023正好是这只股票的编号,sz表示的深圳交易所。因此我们构造的程序结构如下:
步骤1: 从东方财富网获取股票列表;
步骤2: 逐一获取股票代码,并增加到百度股票的链接中,最后对这些链接进行逐个的访问获得股票的信息;
步骤3: 将结果存储到文件。
查看百度个股信息网页的源代码,每只股票的信息在html代码中的存储方式如下
每一个信息源对应一个信息值,即采用键值对的方式进行存储
在python中键值对的方式可以用字典类型
因此,在本项目中,使用字典来存储每只股票的信息,然后再用字典把所有股票的信息记录起来,最后将字典中的数据输出到文件中
代码编写
第一步:获得html网页数据
def getHTMLText(url):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
第二步:html代码解析程序
a标签的href属性中的网址链接里面有每只股票的对应的号码,因此我们只要把网址里面对应股票的号码解析出来即可
html = getHTMLText(stockURL) #获得该页面信息
soup = BeautifulSoup(html,'html.parser')
a = soup.find_all('a') #解析页面找到所有的a标签
对a标签中的每一个进行遍历来进行相关的处理 找到a标签中的href属性,并且判断属性中间的链接,把链接后面的数字取出来,在这里可以使用正则表达式来进行匹配。由于深圳交易所的代码以sz开头,上海交易所的代码以sh开头,股票的数字有6位构成,所以正则表达式可以写为[s][hz]\d{6};
由于在html中有很多的a标签,但是有些a标签中没有href属性,因此上述程序在运行的时候出现异常,所有对上述的程序还要进行try…except来对程序进行异常处理
for i in a :
try:
href = i.attrs['href']
lst.append(re.findall(r'[s][hz]\d{6}',href)[0]
except:
continue
对东方财富网页面解析的完整代码如下
def getStockList(lst,stockURL):
html = getHTMLText(stockURL,'GB2312')
soup = BeautifulSoup(html,'html.parser')
a = soup.find_all('a')
for i in a :
try:
href = i.attrs['href']
#以s开头,中间是h或z,后面再接六位数字
lst.append(re.findall(r'[s][hz]\d{6}',href)[0])
except:
continue
第三步 获得百度股票网链接描述单只股票的信息
股票的信息就存在上图所示的html代码中,因此我们需要对这段html代码进行解析。过程如下:
1.百度股票网的网址为:
https://gupiao.baidu.com/stock/
一只股票信息的网址为:
https://gupiao.baidu.com/stock/sz300023.html
所以只要百度股票网的网址+每只股票的代码即可
因此对getStockList函数返回的列表进行遍历即可,代码如下:
for stock in lst:
url = stockURL + stock +'.html'
html = getHTMLText(url)
2.获得网页的html代码
html = getHTMLText(url)
3.对html代码进行解析
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})
4.股票名称在bets-name标签内,继续解析
infoDict = {}
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称': name.text.split()[0]}) #split:股票名称空格后面的部分
5.观察到股票的其他信息存放在dt和dd标签中,其中dt表示股票信息的键域,dd标签是值域。获取全部的键和值:
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
把获得的键和值按键值对的方式村放入字典中
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
6.把字典中的数据存入外部文件中
with open(fpath,'a',encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
完整代码:
def getStockInfo(lst,stockURL,fpath):
count = 0
for stock in lst:
url = stockURL + stock +'.html'
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html,'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'})
if isinstance(stockInfo,bs4.element.Tag):
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath,'a',encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
count += 1
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
except:
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
traceback.print_exc()
continue
第四步:编写主函数,调用上述函数
def main():
stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
stock_info_url = 'http://gupiao.baidu.com/stock/'
output_file = 'C:/Users/Administrator/Desktop/Python网络爬虫与信息提取/BaiduStockInfo.txt'
slist = []
getStockList(slist,stock_list_url)
getStockInfo(slist,stock_info_url,output_file)
项目完整程序
import requests
from bs4 import BeautifulSoup
import traceback
import re
import bs4
def getHTMLText(url,code='utf-8'): #使用code提高解析效率
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
return r.text
except:
return '爬取失败'
def getStockList(lst,stockURL):
html = getHTMLText(stockURL,'GB2312')
soup = BeautifulSoup(html,'html.parser')
a = soup.find_all('a')
for i in a :
try:
href = i.attrs['href']
#以s开头,中间是h或z,后面再接六位数字
lst.append(re.findall(r'[s][hz]\d{6}',href)[0])
except:
continue
def getStockInfo(lst,stockURL,fpath):
count = 0
for stock in lst:
url = stockURL + stock +'.html'
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html,'html.parser')
stockInfo = soup.find('div',attrs={'class':'stock-bets'}
if isinstance(stockInfo,bs4.element.Tag):
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valueList[i].text
infoDict[key] = val
with open(fpath,'a',encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
count += 1
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
#打印爬取进度
except:
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end='')
traceback.print_exc()
continue
def main():
stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
stock_info_url = 'http://gupiao.baidu.com/stock/'
output_file = 'C:/Users/Administrator/Desktop/Python网络爬虫与信息提取/BaiduStockInfo.txt'
slist = []
getStockList(slist,stock_list_url)
getStockInfo(slist,stock_info_url,output_file)
main()