使用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使用三种方法实现PCA算法
Dec 12 Python
Python找出最小的K个数实例代码
Jan 04 Python
浅谈python中对于json写入txt文件的编码问题
Jun 07 Python
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
Jan 29 Python
详解Numpy中的数组拼接、合并操作(concatenate, append, stack, hstack, vstack, r_, c_等)
May 27 Python
用sqlalchemy构建Django连接池的实例
Aug 29 Python
python实现多线程端口扫描
Aug 31 Python
解决Tensorflow sess.run导致的内存溢出问题
Feb 05 Python
哈工大自然语言处理工具箱之ltp在windows10下的安装使用教程
May 07 Python
Python自定义sorted排序实现方法详解
Sep 18 Python
Python图像读写方法对比
Nov 16 Python
如何用用Python将地址标记在地图上
Feb 07 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
常用的php ADODB使用方法集锦
2008/03/25 PHP
PHP $_FILES中error返回值详解
2014/01/30 PHP
完美解决phpexcel导出到xls文件出现乱码的问题
2016/10/29 PHP
Javascript脚本实现静态网页加密实例代码
2013/11/05 Javascript
防止按钮在短时间内被多次点击的方法
2014/03/10 Javascript
如何用JavaScript定义一个类
2014/09/12 Javascript
JavaScript DOM 学习总结(五)
2015/11/24 Javascript
浅析在javascript中创建对象的各种模式
2016/05/06 Javascript
JavaScript代码性能优化总结(推荐)
2016/05/16 Javascript
原生JS实现图片左右轮播
2016/12/30 Javascript
canvas实现十二星座星空图
2017/02/14 Javascript
Hexo已经看腻了,来手把手教你使用VuePress搭建个人博客
2018/04/26 Javascript
微信小程序swiper左右扩展各显示一半代码实例
2019/12/05 Javascript
JS Array.from()将伪数组转换成数组的方法示例
2020/03/23 Javascript
[01:31:02]TNC vs VG 2019国际邀请赛淘汰赛 胜者组赛BO3 第一场
2019/08/22 DOTA
使用python实现knn算法
2017/12/20 Python
Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法
2018/05/04 Python
在python 中实现运行多条shell命令
2019/01/07 Python
python基于Selenium的web自动化框架
2019/07/14 Python
python实现将两个文件夹合并至另一个文件夹(制作数据集)
2020/04/03 Python
Django 解决新建表删除后无法重新创建等问题
2020/05/21 Python
解决python和pycharm安装gmpy2 出现ERROR的问题
2020/08/28 Python
NUK奶瓶美国官网:NUK美国
2016/09/26 全球购物
草莓网美国官网:Strawberrynet USA
2016/12/11 全球购物
中东最大的在线宠物店:Dubai Pet Food
2020/06/11 全球购物
什么是Oracle的后台进程background processes?都有哪些后台进程?
2012/04/26 面试题
介绍一下Linux文件的记录形式
2013/09/29 面试题
什么是虚拟内存?虚拟内存有什么优势?
2012/02/19 面试题
完美实现CSS垂直居中的11种方法
2021/03/27 HTML / CSS
心得体会开头
2014/01/01 职场文书
汽车专业学生自我评价
2014/01/19 职场文书
关于运动会广播稿50字
2014/10/18 职场文书
八年级上册语文教学计划
2015/01/22 职场文书
2015年高考寄语或鼓励的话
2015/03/23 职场文书
react中的DOM操作实现
2021/06/30 Javascript
Oracle查看表空间使用率以及爆满解决方案详解
2022/07/23 Oracle