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

 更新时间:2018年01月05日 14:12:00   作者:OliverkingLi  
下面小编就为大家分享一篇使用python爬虫实现网络股票信息爬取的demo,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

实例如下所示:

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

优化并且加入进度条显示

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就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 使用django-guardian实现django-admin的行级权限控制的方法

    使用django-guardian实现django-admin的行级权限控制的方法

    这篇文章主要介绍了使用django-guardian实现django-admin的行级权限控制的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • Pytorch 的 LSTM 模型的示例教程

    Pytorch 的 LSTM 模型的示例教程

    本文给大家介绍了Pytorch 的 LSTM 模型的示例教程,文中结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2023-06-06
  • Python混合使用同步和异步函数的方法

    Python混合使用同步和异步函数的方法

    Python是一种非常灵活的编程语言,可以混合使用同步和异步函数来实现更高效的编程。本文将介绍如何在Python中混合使用同步和异步函数,以及如何在不同场景下选择合适的函数,感兴趣的可以了解一下
    2023-03-03
  • Python+OpenCV实现寻找到圆点标定板的角点

    Python+OpenCV实现寻找到圆点标定板的角点

    这篇文章主要为大家详细介绍了Python+OpenCV实现找到圆点标定板所有点后通过距离找两个角点,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
    2022-11-11
  • python错误处理详解

    python错误处理详解

    这篇文章主要介绍了python错误处理详解,本文讲解了try语句、错误堆栈、记录错误、抛出错误等内容,需要的朋友可以参考下
    2014-09-09
  • Python中csv文件的写入与读取方法例子

    Python中csv文件的写入与读取方法例子

    这篇文章主要给大家介绍了关于Python中csv文件的写入与读取方法的相关资料,csv是"Comma-Separated Values(逗号分割的值)"的首字母缩写,它其实和txt文件一样,都是纯文本文件,使用Python来读写csv文件是非常容易的,需要的朋友可以参考下
    2023-09-09
  • python实现植物大战僵尸游戏实例代码

    python实现植物大战僵尸游戏实例代码

    这篇文章主要给大家介绍了关于python实现植物大战僵尸游戏的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • Python结合Flask框架构建一个简易的远程控制系统

    Python结合Flask框架构建一个简易的远程控制系统

    这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还具备实时屏幕截图功能,需要的可以参考下
    2025-03-03
  • 在Python中使用SimpleParse模块进行解析的教程

    在Python中使用SimpleParse模块进行解析的教程

    这篇文章主要介绍了在Python中使用SimpleParse模块进行解析的教程,文章来自于IBM官方的开发者技术文档,需要的朋友可以参考下
    2015-04-04
  • Python3简单爬虫抓取网页图片代码实例

    Python3简单爬虫抓取网页图片代码实例

    这篇文章主要介绍了Python3简单爬虫抓取网页图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08

最新评论