技术路线:分别使用requests库、BeautifulSoup库、RE库
因为不能直接爬取到股票的详细情况,我们本次的爬虫使用的是先在东方财富网上爬取所有股票代码,然后通过百度股市通来模拟查询的方式获得当前股票的信息。
首先写出来整体框架,在进一步优化:import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url):
return ""
def getStockList(lst,stockURL):
return ""
def getStockInfo(lst,stockURL,fpath):
return ""
def main():
stock_list_url='http://quote.eastmoney.com/stocklist.html'#股票大全
stock_info_url='https://gupiao.baidu.com/'#百度股市通
output_file='F://BaiduStockInof.txt'
slist=[]getStockList(slist,stock_list_url)
getStockInfo(slist,stock_info_url,output_file)
main()
框架写出来之后思路基本上就是往里面填东西了!
getHTMLText(url)函数还是简单的爬取文章的HTML界面:def getHTMLText(url):
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
extexcept:
return ""
然后返回到getStockList(lst,stockURL)函数中做分析处理: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
其中使用re库来选择符合条件的股票代码是否符合要求,符合的话加入到lst列表中去.
最后是再次调用当前股票的百度查询页面,然后爬取下来股票中我们所需要的信息: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',sttrs={'class':'stock-bets'})
name = stockInfo.find_all (attrs={'class': 'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList =stockInfo.find_all('dt')value
List=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
这个只是简单的将我们所爬取到的信息存储在文本文档中,接下来我们可以加入一些代码对刚刚的代码进行优化,使得用户更加的友好的使用我们的程序。
with open (fpath, 'a', encoding='utf-8') as f:f.write (str (infoDict) + '\n')count = count + 1print ("\r当前进度: {:.2f}%".format (count * 100 / len (lst)), end="")
加上上一段的代码之后我们就可以在程序的使用阶段看到有不换行的进度条的显示
以及最后爬取下来的结果:
总结
思路很重要
当我们有了一个需求的时候,不要纠结于某个网站。一定要爬取某一个网站的数据是钻牛角尖。我们可以尝试着用不同的方式去获得我们想要的信息,而且我们可以尝试爬取不同端的数据来试试可不可以将数据更加轻松的爬取到。比如pc端的数据不行就尝试着移动端。
优化
代码放在Github上:股票数据爬取 一同乱写,到最后再来重新优化。而不是首先整个代码的架构,然后调用、优化、最后在考虑整体的鲁棒性。
思考
思考是最重要的,就好像最后优化加入一个爬取百分比的时候,如何才能够实现进度条的不换行输出呢?这些都是需要思考的。只有不断的思考才能够培养自己的些许能力吧!每天才能够不断的进步。
代码放在Github上:股票数据爬取