python利用re,bs4,requests模块获取股票数据

作者:baagee 时间:2022-05-07 05:02:23 

今天闲来无聊无意间看到了百度股票,就想着用python爬一下数据,于是就找到了东方财经网,结合这两个网站,写了一个小爬虫,数据保存在文件中,比较简单的示例,就当做用来练习正则表达式和BeautifulSoupl了。

首先页面分析,打开东方财经网股票列表页,

python利用re,bs4,requests模块获取股票数据

和百度股票详情页 ,右键查看网页源代码,

python利用re,bs4,requests模块获取股票数据

网址后面的代码就是股票代码,所以打算先获取股票代码,然后获取详情,废话少说,直接上代码吧:


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()

来源:https://baagee.vip/index/article/id/85.html

标签:python,re,bs4,requests,模块,获取,股票数据
0
投稿

猜你喜欢

  • dl+ol应用

    2008-06-21 17:04:00
  • nlp计数法应用于PTB数据集示例详解

    2023-10-26 17:24:07
  • python sorted方法和列表使用解析

    2021-07-09 05:32:41
  • 使用python实现希尔、计数、基数基础排序的代码

    2023-07-12 09:02:24
  • python中把嵌套的列表合并成一个列表方法总结

    2022-06-07 04:11:22
  • 详解pyenv下使用python matplotlib模块的问题解决

    2023-08-08 20:25:01
  • Python简单生成随机姓名的方法示例

    2023-04-26 19:35:58
  • 谈谈FACEBOOK的一处产品细节

    2008-03-11 11:05:00
  • CSS框架的利与弊

    2007-12-06 12:59:00
  • 基于prototype扩展的JavaScript常用函数库

    2023-08-24 15:09:57
  • Go语言中使用反射的方法

    2023-07-22 22:31:48
  • 简单了解python变量的作用域

    2022-07-21 13:10:08
  • ASP动态包含文件的改进方法

    2009-01-05 12:22:00
  • Dreamweaver量身打造Wordpress留言板(二)

    2009-12-12 17:35:00
  • PHP substr()函数参数解释及用法讲解

    2023-11-24 11:47:56
  • 网页上的广告条设计思考

    2008-06-29 14:16:00
  • python一行代码合并了162个Word文件

    2022-07-24 04:20:57
  • pandas 使用apply同时处理两列数据的方法

    2021-09-27 07:35:30
  • python实现excel转置问题详解

    2023-06-27 23:27:27
  • Python爬取豆瓣视频信息代码实例

    2021-10-28 06:41:46
  • asp之家 网络编程 m.aspxhome.com