股票HTML网页分析:

东方财富网可以看到股票信息:

http://quote.eastmoney.com/stocklist.html

查看源代码:

<li><a target="_blank" href="http://quote.eastmoney.com/sh201008.html">R001(201008)</a></li>
<li><a target="_blank" href="http://quote.eastmoney.com/sh201010.html">R004(201010)</a></li>
<li><a target="_blank" href="http://quote.eastmoney.com/sh202001.html">RC001(202001)</a></li>

可以在href中提取股票的代码,
想了解股票的具体信息,需要去百度股票查找,方法为:
'https://gupiao.baidu.com/stock/股票代码.html
查看具体股票的源代码:

<div class="stock-info" data-spm="2"><div class="stock-bets"><h1><a class="bets-name" href="/stock/sz300388.html">国祯环保 (<span>300388</span>)</a><span class="state f-up">已休市 2017-09-29  15:00:03</span></h1><div class="price s-stop "><strong  class="_close">--</strong><span>--</span><span>--</span></div><div class="bets-content"><div class="line1"><dl><dt>今开</dt><dd class="">19.92</dd></dl><dl><dt>成交量</dt><dd>8917手</dd></dl><dl><dt>最高</dt><dd class="s-up">20.15</dd></dl><dl><dt>涨停</dt><dd class="s-up">21.96</dd></dl><dl><dt>内盘</dt><dd>4974手</dd></dl><dl><dt>成交额</dt><dd>1786.10万</dd></dl><dl><dt>委比</dt><dd>-50.69%</dd></dl><dl><dt>流通市值</dt><dd>59.98亿</dd></dl><dl><dt class="mt-1">市盈率<sup>MRQ</sup></dt><dd>50.59</dd></dl><dl><dt>每股收益</dt><dd>0.20</dd></dl><dl><dt>总股本</dt><dd>3.06亿</dd></dl><div class="clear"></div></div><div class="line2"><dl><dt>昨收</dt><dd>19.96</dd></dl><dl><dt>换手率</dt><dd>0.30%</dd></dl><dl><dt>最低</dt><dd class="s-down">19.92</dd></dl><dl><dt>跌停</dt><dd class="s-down">17.96</dd></dl><dl><dt>外盘</dt><dd>3943手</dd></dl><dl><dt>振幅</dt><dd>1.15%</dd></dl><dl><dt>量比</dt><dd>0.11</dd></dl><dl><dt>总市值</dt><dd>61.35亿</dd></dl><dl><dt>市净率</dt><dd>3.91</dd></dl><dl><dt>每股净资产</dt><dd>5.14</dd></dl><dl><dt>流通股本</dt><dd>2.99亿</dd></dl></div><div class="clear"></div></div></div>

发现股票名称在class="bets-name"的a标签中,其他的数据都在dt和dd标签中

方法一:采用bs4库和正则表达式

import requests
from bs4 import BeautifulSoup
import re#优化,可以减少程序判断编码所花费的时间
def getHTMLText(url, code='UTF-8'):try:r = requests.get(url)r.raise_for_status()r.encoding = codereturn r.textexcept:return ""def getStockList(url, stockList):html = getHTMLText(url, 'GB2312')soup = BeautifulSoup(html, 'html.parser')aInformaton = soup.find_all('a')for ainfo in aInformaton:try:stockList.append(re.findall(r'[s][hz]\d{6}', ainfo.attrs['href'])[0])except:continuedef getStockInformation(detailUrl, outputFile, stockList):count = 0for name in stockList:count = count + 1stockUrl = detailUrl + name + '.html'html = getHTMLText(stockUrl)try:if html == "":continuestockDict = {}soup = BeautifulSoup(html, 'html.parser')stockinfo = soup.find('div', attrs={'class': 'stock-bets'})stockname = stockinfo.find('a', attrs={'class': 'bets-name'})# 当标签内部还有标签时,利用text可以得到正确的文字,利用string可能会产生NonestockDict["股票名称"] = stockname.text.split()[0]stockKey = stockinfo.find_all('dt')stockValue = stockinfo.find_all('dd')for i in range(len(stockKey)):stockDict[stockKey[i].string] = stockValue[i].string#\r移动到行首,end=""不进行换行print("\r{:5.2f}%".format((count / len(stockList) * 100)), end='')#追加写模式'a'f = open(outputFile, 'a')f.write(str(stockDict) + '\n')f.close()except:print("{:5.2f}%".format((count / len(stockList) * 100)), end='')continuedef main():listUrl = 'http://quote.eastmoney.com/stocklist.html'detailUrl = 'https://gupiao.baidu.com/stock/'outputFile = 'C:/Users/Administrator/Desktop/out.txt'stockList = []getStockList(listUrl, stockList)getStockInformation(detailUrl, outputFile, stockList)
main()

方法2.采用Scrapy框架和正则表达式库

(1)建立工程和Spider模板(保存为stocks.py文件)

在命令行中进入:E:\PythonProject\BaiduStocks

输入:scrapy startproject BaiduStocks   建立了scrapy工程

输入:scrapy genspider stocks baidu.com 建立spider模板,baidu.com是指爬虫限定的爬取域名,在stocks.py文件删去即可

(2)编写spider爬虫(即stocks.py文件)

采用css选择器,可以返回选择的标签元素,通过方法extract()可以提取标签元素为字符串从而实现匹配正则表达式的处理

正则表达式详解:

<a class="bets-name" href="/stock/sz300388.html">国祯环保 (<span>300388</span>)</a>

re.findall('.*\(', stockname)[0].split()[0] + '('+re.findall('\>.*\<', stockname)[0][1:-1]+')'

匹配结果:国祯环保(300388)

因为'('为正则表达式语法里的基本符号,所以需要转义

正则表达式从每行开始匹配,匹配之后返回['            国祯环保 ('],采用split将空白字符分割,返回['国祯环保',‘(’]

# -*- coding: utf-8 -*-
import scrapy
import reclass StocksSpider(scrapy.Spider):name = 'stocks'start_urls = ['http://quote.eastmoney.com/stocklist.html']def parse(self, response):fo=open(r'E:\PythonProject\BaiduStocks\oo.txt','a')#fo.write(str(response.css('a').extract()))count=0for href in response.css('a').extract():try:if count == 300:breakcount=count+1stockname=re.findall(r'[s][hz]\d{6}',href)[0]stockurl='https://gupiao.baidu.com/stock/' + stockname + '.html'#fo.write(stockurl)yield scrapy.Request(url= stockurl,headers={"User-Agent":"Chrome/10"} ,callback=self.stock_parse)except:continuepassdef stock_parse(self,response):ffo=open(r'E:\PythonProject\BaiduStocks\stockparse.txt','a')stockDict={}#提取标签中class="stock-bets"的标签元素stockinfo=response.css('.stock-bets')#将提取出来的标签转化为字符串列表,然后取第一个stockname=stockinfo.css('.bets-name').extract()[0]#ffo.write(stockname)keyList=stockinfo.css('dt').extract()#ffo.write(str(keyList))valueList=stockinfo.css('dd').extract()stockDict['股票名称'] = re.findall('.*\(', stockname)[0].split()[0] + '('+re.findall('\>.*\<', stockname)[0][1:-1]+')'for i in range(len(keyList)):stockkey=re.findall(r'>.*</dt>',keyList[i])[0][1:-5]stockvalue=re.findall(r'>.*</dd>',valueList[i])[0][1:-5]stockDict[stockkey]=stockvalueyield stockDict

(3)编写PipeLine(即pipelines.py文件)

系统自动生成了Item处理类BaiduStocksPipeline,我们不采用系统生成,新建一个BaiduStocksinfoPipeline类,并书写Item处理函数

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlclass BaidustocksPipeline(object):def process_item(self, item, spider):return itemclass BaidustocksinfoPipeline(object):#爬虫打开时执行def open_spider(self,spider):self.f=open(r'E:\PythonProject\BaiduStocks\BaiduStocks\asdqwe.txt','a')# 爬虫关闭时执行def close_spider(self,spider):self.f.close()#处理Item项def process_item(self,item,spider):try:self.f.write(str(item)+'\n')except:passreturn item

此时要修改配置文件setting.py文件

ITEM_PIPELINES = {'BaiduStocks.pipelines.BaidustocksinfoPipeline': 300,
}

(4)运行爬虫:scrapy crawl stocks

python 股票数据爬取(两种方法)相关推荐

  1. python如何爬虫股票数据_简单爬虫:东方财富网股票数据爬取(python_017)

    需求:将东方财富网行情中心的股票数据爬取下来,包括上证指数.深圳指数.上证A股.深圳A股.新股.中小板.创业板 等 一.目标站点分析 东方财富网的行情中心页面包含了所有股票信息.在左侧的菜单栏中包含了 ...

  2. 使用python进行股票数据爬取中的时间限制和策略

    股票数据爬取中的时间限制和策略 在进行股票数据爬取时,时间限制和策略是非常重要的考虑因素.本文将介绍两个与此相关的函数:is_trade_day()和stock_work_day(). is_trad ...

  3. python怎么模拟浏览器交互_干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏)...

    今天为大家带来的内容是:干货分享:python爬虫模拟浏览器的两种方法实例分析(赶紧收藏) 文章主要介绍了python爬虫模拟浏览器的两种方法,结合实例形式分析了Python爬虫模拟浏览器的两种常见操 ...

  4. 基于python的数据爬取与分析_基于Python的网站数据爬取与分析的技术实现策略

    欧阳元东 摘要:Python为网页数据爬取和数据分析提供了很多工具包.基于Python的BeautifulSoup可以快速高效地爬取网站数据,Pandas工具能方便灵活地清洗分析数据,调用Python ...

  5. python实现数据爬取——糗事百科爬虫项目

    python实现数据爬取--糗事百科爬虫项目 # urllib.request 请求模块 import urllib.request # re 模块使 Python 语言拥有全部的正则表达式功能. i ...

  6. python与excel做数据可视化-用Python进行数据可视化的10种方法

    原标题:用Python进行数据可视化的10种方法 2015-11-19 关于转载授权 大数据文摘作品,欢迎个人转发朋友圈,自媒体.媒体.机构转载务必申请授权,后台留言"机构名称+转载&quo ...

  7. python自带的shell是什么-python中执行shell的两种方法总结

    一.使用python内置commands模块执行shell commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态: ...

  8. Python网络数据爬取及分析-智联招聘

    python网络数据爬取及分析-智联招聘 一. 数据爬取 智联招聘是一家面向大型公司和快速发展的中小企业提供一站式专业人力资源的公司,可在智联招聘网站上根据不同城市.不同职位需求搜索得到相关招聘信息. ...

  9. 爬虫项目3 - 股票数据爬取

    爬虫项目3 - 股票数据爬取 步骤 步骤 爬取股票名和股票列表,使用gucheng网进行爬取,网址: https://hq.gucheng.com/gpdmylb.html import reques ...

最新文章

  1. 光子人工智能芯片助“中国芯”换道超车
  2. easyui treegrid idField 所在属性中值有花括号(如Guid)当有鼠标事件时会报错,行记录一下...
  3. 怎样为Linux内核打补丁
  4. VTK:vtkCompositePolyDataMapper2用法实战
  5. C++多态案例二-制作饮品
  6. Arcgis for JS扩展GraphicLayer实现区域对象的聚类统计与展示
  7. C语言编写工资管理系统类似学生管理系统
  8. Linux监控命令之==sar
  9. Python 告诉你,情人节该送什么礼物?
  10. Ubuntu中使用pip3报错
  11. 老马的原创空间搬家通告
  12. 学习微软企业库存心得--总结
  13. info There appears to be trouble with your network connection. Retrying...
  14. Windows 内存机制说明
  15. 数据结构和算法 第一章 综述(1)
  16. Inc. magazine年度公司Evernote: 小小记事本如何风靡全球
  17. cocos creator3.3.0休闲游戏(云浮消消乐)源码H5+安卓+IOS三端源码
  18. 基于HTML和HTML5
  19. 你该选择哪种编程语言来开发App呢?
  20. 音视频解封装:MP4核心Box详解及H264AAC打包方案

热门文章

  1. 文献综述搜索利器——HistCite
  2. windowsserver可以ping通ip但telnet端口失败问题排查处理
  3. MATLAB数学建模(4)-数据的统计和分析
  4. 计算机教育软件参评作品例子,2018年东莞计算机教育软件评审活动.doc
  5. 工业建模和游戏建模有什么区别?哪个发展前景更好?
  6. 关于阿里云域名的购买和DNS解析教程过程详细
  7. 2021 年最新前后端免费编程学习视频
  8. Java和web前端学哪个好?哪个更有前景
  9. 192.168.8.1手机登陆_192.168.8.1登录入口手机登陆?
  10. 在win10中开启64位ie浏览器的方法(IE11)