目录
三、“股票数据定向爬虫”实例
1、“股票数据定向爬虫”实例介绍
(1)功能描述
目标:获取上交所和深交所所有股票的名称和交易信息。
输出:保存到文件中。
技术路线:requests-bs4-re。
(2)候选数据网站的选择
①新浪股票:http://finance.sina.com.cn/stock/。
②百度股票:https://gupiao.baidu.com/stock/。
备注:原来的百度股票网页链接已失效;故更改为https://so.cfi.cn/so.aspx?txquery=。原来的东方财富网网页链接已无法爬取数据;故更改为http://quote.eastmoney.com/stock_list.html#sh。
选取原则:股票信息静态存在于HTML页面中,非js代码生成,没有Robots协议限制。
选取方法:浏览器F12,源代码查看等。
选取心态:不要纠结于某个网站,多找信息源尝试。
(3)程序的结构设计
步骤1:从东方财富网获取股票列表。
步骤2:根据股票列表逐个到百度股票获取个股信息。
步骤3:将结果存储到文件。
2、“股票数据定向爬虫”实例编写
# “股票数据定向爬虫”实例编写
# 错误
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def getStockList(lst, stockURL):
html = getHTMLText(stockURL)
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('a')
for i in a:
try:
href = i.attrs['href']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
def getStockInfo(lst, stockURL, fpath):
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'})
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')
except:
traceback.print_exc()
continue
def main():
stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'H://python//Web crawler//BaiduStockInfo.txt'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()
# “股票数据定向爬虫”实例编写
# 正确
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url, code='utf-8'):
try:
r = requests.get(url, timeout=30)
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']
lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
except:
continue
return lst
def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html == "" or html == None:
continue
l = []
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('table', attrs={'class': 'quote'})
trans = str(stockInfo)
reg = r'<td>(.*?)</td>'
texty = re.compile(reg)
s1 = re.findall(texty, trans)[1::]
reg1 = r'<td>(.*?)<a'
texty1 = re.compile(reg1)
s2 = re.findall(texty1, trans)[0]
for i in s1:
s = i.replace("\u3000", "")
x = s.replace("<span style=\"color:rgb(0,102,0)\">", "")
b = x.replace("<span style=\"color:rgb(0,0,0)\">", "")
a = b.replace("</span>", "")
c = a.replace("<span style=\"color:rgb(255,0,0)\">", "")
l.append(c)
w = ",".join(l)
if l == []:
continue
with open(fpath, 'a', encoding='utf-8') as f:
f.write(s2 + '\u3000')
f.write(w + '\n')
count = count + 1
print("\r当前速度:{:.2f}%".format(count * 100 / len(lst)), end="") # 增加动态进度显示。
except:
count = count + 1
print("\r当前速度:{:.2f}%".format(count * 100 / len(lst)), end="") # 增加动态进度显示。
continue
def main():
stock_list_url = 'http://quote.eastmoney.com/stock_list.html#sh'
stock_info_url = 'https://so.cfi.cn/so.aspx?txquery=sz501310'
output_file = 'H://python//Web crawler//BaiduStockInfo.txt'
slist = []
getStockList(slist, stock_list_url)
print(getStockInfo(slist, stock_info_url, output_file))
main()
备注:原来的网页链接(http://quote.eastmoney.com/stock_list.html#sh)爬取时间太长;故更改为https://so.cfi.cn/so.aspx?txquery=sz501310,等号后的sz501310是对应每个股的代号。运行时间大约2000分钟。(运行时间没写错,确实很长)
3、“股票数据定向爬虫”实例优化
(1)速度提高:编码识别的优化
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding # 编码识别的优化。
return r.text
except:
return ""
(2)体验提高:增加动态进度显示
with open(fpath, 'a', encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
count = count + 1
print("\r当前速度:{:.2f}%".format(count * 100 / len(lst)), end="") # 增加动态进度显示。
except:
count = count + 1
print("\r当前速度:{:.2f}%".format(count * 100 / len(lst)), end="") # 增加动态进度显示。
continue