環境:windows10 ,Python 3.5.2
安裝教程到處都是,不做贅述,爬蟲實現股票分析(一)只講解了怎么去東方財富網爬取下來6開頭股票的信息(包括歷史信息)
知識點:正則表達式,python簡單語法,東方財富網相關結構
實測實現代碼:
#導入需要使用到的模塊
import urllib
import urllib.request
import re
import os
#爬蟲抓取網頁函數
def getHtml(url):
html = urllib.request.urlopen(url).read()
html = html.decode('gbk')
return html
#獲取所有的股票編號,正則表達式帶()時,返回值只包含括號里內容,即股票編號數組
def getStackCode(html):
s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
pat = re.compile(s)
code = pat.findall(html)
return code
Url = 'http://quote.eastmoney.com/stocklist.html'#東方財富網股票網址
filepath = 'D:\\data\\python\\stock\\'#定義數據文件保存路徑
#進行抓取
code = getStackCode(getHtml(Url))
#獲取所有以6開頭的股票代碼的集合
CodeList = []
for item in code:
if item[0]=='6':
CodeList.append(item)
#將網頁上文件下載並保存到本地csv文件,注意日期
for code in CodeList:
print('正在獲取股票%s數據'%code)
url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
'&end=20190228&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
urllib.request.urlretrieve(url, filepath+code+'.csv')
注意點:
1.findall 使用正則表達式,並且正則表達式帶()時,返回值只包含括號里內容,即股票編號數組
2.一定要import urllib.request,只import urllib不行
3.filepath = 'D:\\data\\python\\stock\\' 的 filepath 目錄要存在,不然就用下面的形式:
if not os.path.exists(file_path): os.mkdir(file_path)
最終執行就可以實現股票的歷史信息了,大概如下:

具體內容如下:

是不是很神奇,短短幾行代碼實現如此強大的功能,是不是有了很強的學習動力
