今天閑來無聊無意間看到了百度股票,就想著用python爬一下數據,于是就找到了東方財經網,結合這兩個網站,寫了一個小爬蟲,數據保存在文件中,比較簡單的示例,就當做用來練習正則表達式和BeautifulSoupl了。
首先頁面分析,打開東方財經網股票列表頁,
和百度股票詳情頁 ,右鍵查看網頁源代碼,
網址后面的代碼就是股票代碼,所以打算先獲取股票代碼,然后獲取詳情,廢話少說,直接上代碼吧:
import re import requests from bs4 import BeautifulSoup #獲取html def getHtml(url): try: req=requests.get(url) req.raise_for_status() req.encoding=req.apparent_encoding return req.text except : print('getHtml失敗') #獲取股票代碼 def getStockList(lst,stockUrl): html=getHtml(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): count=0 for stock in lst: url=stockUrl+stock+'.html' html=getHtml(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') count+=1 print('\r當前速度:{:.2f}%'.format(count*100/len(lst)),end='') except: count+=1 print('\r當前速度e:{:.2f}%'.format(count*100/len(lst)),end='') continue def main(): stockListUrl='http://quote.eastmoney.com/stocklist.html' stockInfotUrl='https://gupiao.baidu.com/stock/' outPutFile='D:\python\shuju\stockInfo.txt' slist=[] getStockList(slist,stockListUrl) getStockInfo(slist,stockInfotUrl,outPutFile) main()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
