日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python利用re,bs4,requests模塊獲取股票數據

系統 1736 0

今天閑來無聊無意間看到了百度股票,就想著用python爬一下數據,于是就找到了東方財經網,結合這兩個網站,寫了一個小爬蟲,數據保存在文件中,比較簡單的示例,就當做用來練習正則表達式和BeautifulSoupl了。

首先頁面分析,打開東方財經網股票列表頁,

python利用re,bs4,requests模塊獲取股票數據_第1張圖片

和百度股票詳情頁 ,右鍵查看網頁源代碼,

python利用re,bs4,requests模塊獲取股票數據_第2張圖片

網址后面的代碼就是股票代碼,所以打算先獲取股票代碼,然后獲取詳情,廢話少說,直接上代碼吧:

            
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元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 甘泉县| 武汉市| 安庆市| 兰坪| 黎川县| 延津县| 肇庆市| 雅江县| 成都市| 昌黎县| 绩溪县| 江阴市| 山东| 泾阳县| 新宁县| 吴旗县| 建始县| 拜泉县| 迁西县| 泽州县| 福安市| 娱乐| 大关县| 文化| 苗栗县| 台北市| 襄汾县| 察隅县| 广宁县| 温泉县| 玉树县| 巴东县| 鄂州市| 太康县| 雅江县| 鄂托克旗| 通化市| 绥棱县| 丹江口市| 岚皋县| 苍溪县|