使用python爬虫实现网络股票信息爬取的demo


Posted in Python onJanuary 05, 2018

实例如下所示:

import requests
from bs4 import BeautifulSoup
import traceback
import re
 
def getHTMLText(url):
 try:
  r = requests.get(url)
  r.raise_for_status()
  r.encoding = r.apparent_encoding
  return r.text
 except:
  return ""
 
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
 
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',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' )
  except:
   traceback.print_exc()
   continue
 
def main():
 stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
 stock_info_url = 'https://gupiao.baidu.com/stock/'
 output_file = 'D:/BaiduStockInfo.txt'
 slist=[]
 getStockList(slist, stock_list_url)
 getStockInfo(slist, stock_info_url, output_file)
 
main()

使用python爬虫实现网络股票信息爬取的demo

优化并且加入进度条显示

import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url, code="utf-8"):
 try:
  r = requests.get(url)
  r.raise_for_status()
  r.encoding = code
  return r.text
 except:
  return ""
def getStockList(lst, stockURL):
 html = getHTMLText(stockURL, "GB2312")
 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 = getHTMLText(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 = count + 1
    print("\r当前进度: {:.2f}%".format(count * 100 / len(lst)), end="")
  except:
   count = count + 1
   print("\r当前进度: {:.2f}%".format(count * 100 / len(lst)), end="")
   continue
def main():
 stock_list_url = 'http://quote.eastmoney.com/stocklist.html'
 stock_info_url = 'https://gupiao.baidu.com/stock/'
 output_file = 'BaiduStockInfo.txt'
 slist = []
 getStockList(slist, stock_list_url)
 getStockInfo(slist, stock_info_url, output_file)
main()

使用python爬虫实现网络股票信息爬取的demo

以上这篇使用python爬虫实现网络股票信息爬取的demo就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python标准库defaultdict模块使用示例
Apr 28 Python
Python中pygame安装方法图文详解
Nov 11 Python
Python中的with语句与上下文管理器学习总结
Jun 28 Python
Python实现手写一个类似django的web框架示例
Jul 20 Python
使用python根据端口号关闭进程的方法
Nov 06 Python
Python同步遍历多个列表的示例
Feb 19 Python
pyqt5 删除layout中的所有widget方法
Jun 25 Python
python 利用pyttsx3文字转语音过程详解
Sep 25 Python
Pytorch十九种损失函数的使用详解
Apr 29 Python
python右对齐的实例方法
Jul 05 Python
Python如何执行精确的浮点数运算
Jul 31 Python
python单例模式的应用场景实例讲解
Feb 24 Python
简单实现python收发邮件功能
Jan 05 #Python
5款非常棒的Python工具
Jan 05 #Python
Python基于列表模拟堆栈和队列功能示例
Jan 05 #Python
Django 2.0版本的新特性抢先看!
Jan 05 #Python
微信跳一跳游戏python脚本
Apr 01 #Python
Python基于列表list实现的CRUD操作功能示例
Jan 05 #Python
django 2.0更新的10条注意事项总结
Jan 05 #Python
You might like
基于mysql的论坛(6)
2006/10/09 PHP
php 魔术函数使用说明
2010/02/21 PHP
php trim 去除空字符的定义与语法介绍
2010/05/31 PHP
深入PHP empty(),isset(),is_null()的实例测试详解
2013/06/06 PHP
PHP 7的一些引人注目的新特性简单介绍
2015/11/08 PHP
微信 getAccessToken方法详解及实例
2016/11/23 PHP
PHP实现微信小程序用户授权的工具类示例
2019/03/05 PHP
PHP文件后缀不强制为.php方法
2019/03/31 PHP
PHP设计模式概论【概念、分类、原则等】
2020/05/01 PHP
基于jquery封装的一个js分页
2011/11/15 Javascript
js 函数调用模式小结
2011/12/26 Javascript
《JavaScript高级程序设计》阅读笔记(一) ECMAScript基础
2012/02/27 Javascript
自己做的模拟模态对话框实现代码
2012/05/23 Javascript
javascript生成json数据简单示例分享
2014/02/14 Javascript
jQuery实现表格行上下移动和置顶效果
2015/06/05 Javascript
深入解析js轮播插件核心代码的实现过程
2017/04/14 Javascript
分享Bootstrap简单表格、表单、登录页面
2017/08/04 Javascript
基于JS实现前端压缩上传图片的实例代码
2019/05/14 Javascript
layui复选框的全选与取消实现方法
2019/09/02 Javascript
vue与django集成打包的实现方法
2019/11/11 Javascript
解决vue项目 build之后资源文件找不到的问题
2020/09/12 Javascript
详解Python中的文件操作
2016/08/28 Python
python,Django实现的淘宝客登录功能示例
2019/06/12 Python
Python 使用folium绘制leaflet地图的实现方法
2019/07/05 Python
通过Python实现一个简单的html页面
2020/05/16 Python
基于opencv实现简单画板功能
2020/08/02 Python
教你如何用python操作摄像头以及对视频流的处理
2020/10/12 Python
美国领先的家居装饰和礼品商店:Kirkland’s
2017/01/30 全球购物
大学生求职中的自我评价
2013/10/01 职场文书
2014年十一国庆节爱国演讲稿
2014/09/23 职场文书
2014年班主任工作总结
2014/11/08 职场文书
物业客服专员岗位职责
2015/04/07 职场文书
2019年世界儿童日宣传标语
2019/11/22 职场文书
Python实现byte转integer
2021/06/03 Python
TV动画《史上最强大魔王转生为村民A》番宣CM公布
2022/04/01 日漫
PyCharm 配置SSH和SFTP连接远程服务器
2022/05/11 Python