前言

我服了,这几天,怎么涨两天还不够跌一次,害。希望这个可以帮到自己!

“股票数据定向爬虫”实例介绍

功能描述

目标:获取上交所和深交所所有股票的名称和交易信息

输出:保存到文件中

技术路线:requests‐bs4‐re

候选数据网站的选择

新浪股票:http://finance.sina.com.cn/stock/

百度股票:https://gupiao.baidu.com/stock/

选取原则:股票信息静态存在于HTML页面中,非js代码生成;没有Robots协议限制

选取方法:浏览器 F12,源代码查看等

选取心态:不要纠结于某个网站,多找信息源尝试

请查看视频理解网站的选取过程

数据网站的确定

获取股票列表:

东方财富网:http://quote.eastmoney.com/stocklist.html

获取个股信息:

百度股票:https://gupiao.baidu.com/stock/

单个股票https://gupiao.baidu.com/stock/sz002439.html

程序的结构设计

步骤1:从东方财富网获取股票列表

步骤2:根据股票列表逐个到百度股票获取个股信息

步骤3:将结果存储到文件

“股票数据定向爬虫”实例编写

main()

import requests from bs4 import BeautifulSoup import traceback import re def getHTMLText(url): return "" def getStockList(lst, stockURL): return "" def getStockInfo(lst, stockURL, fpath): return "" def main(): stock_list_url = 'http://quote.eastmoney.com/stocklist.html' stock_info_url = 'http://gupiao.baidu.com/stock/' output_file = 'D:/BaiduStockInfo.txt' slist=[] getStockList(slist, stock_list_url) getStockInfo(slist, stock_info_url, output_file) main()

def getHTMLText(url): try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return ""

东方财富网:http://quote.eastmoney.com/stocklist.html

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

百度股票:https://gupiao.baidu.com/stock/

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

全代码见文末附录

“股票数据定向爬虫”实例优化

如何提高用户体验?

单元小结

附录(本节代码)

#CrawBaiduStocksA.py 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 = 'http://gupiao.baidu.com/stock/' output_file = 'D:/BaiduStockInfo.txt' slist=[] getStockList(slist, stock_list_url) getStockInfo(slist, stock_info_url, output_file) main()

#CrawBaiduStocksB.py 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 = 'http://gupiao.baidu.com/stock/' output_file = 'D:/BaiduStockInfo.txt' slist=[] getStockList(slist, stock_list_url) getStockInfo(slist, stock_info_url, output_file) main()

本文地址:https://blog.csdn.net/haojie_duan/article/details/108228168

希望与广大网友互动??

点此进行留言吧!

python如何爬虫股票数据_python爬虫实例,股票数据定向爬虫相关推荐

  1. python简单好看的代码_Python新手写出漂亮的爬虫代码1

    初到大数据学习圈子的同学可能对爬虫都有所耳闻,会觉得是一个高大上的东西,仿佛九阳神功和乾坤大挪移一样,和别人说"老子会爬虫",就感觉特别有逼格,但是又不知从何入手,这里,博主给大家 ...

  2. python分析股票主力_python如何获取股票数据,python股票分析系统

    内容导航: Q1:怎样用python处理股票 用Python处理股票需要获取股票数据,以国内股票数据为例,可以安装Python的第三方库:tushare:一个国内股票数据获取包.可以在百度中搜索&qu ...

  3. python 微信数据_python 处理微信对账单数据的实例代码

    下面一段代码给大家介绍python 处理微信对账单数据,具体代码如下所示: #下载对账单并存储到数据库 @app.route("/bill/",methods=["GET ...

  4. python的json格式输出_python中json格式数据输出实现方式

    python中json格式数据输出实现方式 主要使用json模块,直接导入import json即可. 小例子如下: #coding=UTF-8 import json info={} info[&q ...

  5. python读取mysql中表内数据_Python读取MySQL表数据的方法介绍

    这篇文章主要为大家详细介绍了Python如何读取MySQL数据库表数据,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 本文实例为大家分享了Python读取MySQL数据库表数据的具体代码,供大家参 ...

  6. python保存图片到指定路径_python 抓取页面数据,并保存图片文本到指定目录文件夹...

    这个爬虫主要利用scrapy+beautifulsoup完成,其中图片保存碰到了一个大坑,花了一天的时间才解决. 大坑就是:在抓取文章页指定区域所有图片的时候,刚好那块区域的图片所有页面都一样,导致图 ...

  7. python处理金融数据_Python 数据分析中金融数据的来源库和简单操作

    金融数据 数据分析离不开数据的获取,这里介绍几种常用的获取金融方面数据的方法. pandas-datareader pandas-datareader 库包含了全球最著名的几家公司所整理的金融数据,这 ...

  8. python中df是什么_python数据分析之pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]...

    1 引言 Pandas是作为Python数据分析著名的工具包,提供了多种数据选取的方法,方便实用.本文主要介绍Pandas的几种数据选取的方法. Pandas中,数据主要保存为Dataframe和Se ...

  9. pythonurllib库获取yahoo财经数据_Python获取Yahoo股票数据

    1. Yahoo股票 Yahoo财经提供国内外的股票数据,其请求URL格式如下: http://ichart.finance.yahoo.com/table.csv?a=03&b=12& ...

  10. python导入哨兵数据_Python 下载哨兵Sentinel数据(Sentinel-1~3)

    哨兵数据目前应用广泛,空间分辨.光谱分辨率都比较高.目前数据下载部分包括官网和Python程序下载. 其中哨兵1和2数据下载网上已经有非常详细的记录,链接如下:Python中使用sentinelsat ...

最新文章

  1. Swoft 2 Beta 发布,基于 Swoole 的云原生协程框架
  2. SAP CRM呼叫中心搜索Max hit的配置点
  3. 一人之力也能抬起一辆大型箱车?
  4. Linux iptables 配置详解
  5. 数组的合并和升序排列_leetcode 33 搜索旋转排序数组
  6. jsp单选按钮传值传递jsp_一篇彻底搞懂jsp
  7. [转载] 中华典故故事(孙刚)——01 天要下雨_娘要嫁人
  8. SQL Server到底需要使用哪些端口
  9. Error running ‘Tomcat8.5‘ port out of range-1 (moments ago)
  10. 业务分析报告与数据可视化报表
  11. LeCo-83.删除排序链表中的重复元素
  12. 二十九、K8s最小服务漏洞3-gVisor沙箱
  13. jemter使用beanshell的几种方法
  14. Web自动化测试教程
  15. 原生js制作扫雷-自定义难度
  16. 电影-满城尽带黄金甲
  17. java 捕获 nullpointerexception,Android上无法捕获java.lang.NullPointerException
  18. NOJ1076 机器狗组装费用 贪心
  19. AndroidO Treble架构下的变化
  20. java 函数fun_c语言中fun用法详解_后端开发

热门文章

  1. 云平台短信验证码通知短信java/php/.net开发实现
  2. CAN 网络通信矩阵
  3. 转载:CAN:CAN矩阵、CAN网络、DBC、MDF关系
  4. 小酷智慧地图3D导览v1.0.82 打卡定位 地图打卡
  5. 解释:什么是CPC,CPA,CVR,CTR,ROI? 营销、广告、淘宝 术语
  6. 如何提升广告ROI?转化跟踪了解一下
  7. 2019双十一大战:苏宁的“1小时场景生活圈”诱惑
  8. 介绍李三忠老师和吴自银老师的专著
  9. resnet—吴恩达
  10. ValueError: cannot reshape array of size xxx into shape (xxx,xxx,xxx)解决方法