本文共 4732 字,大约阅读时间需要 15 分钟。
再看看单个股票网页的网址,只需要在对应的网页加上对应的股票编码就可以获得
最后再看看但个网页的股票的具体的价格信息,分别在对应的dd和tt标签中,名称在属性为“bets—name”的属性中
首先打开如下位置的文件
def parse(self, response): for href in response.css('a::attr(href)').extract(): # 提取其中所有的a标签,并获取其中href连接 try: stock = re.findall(r'[s][hz]\d{6}',href)[0] # 通过正则表达式,获得相关的股票的代码 url = 'https://gupiao.baidu.com/stock/' + stock + '.html' # 生成百度股票的html网页 yield scrapy.Request(url,callback=self.parse_stock) # 根据生成的网页在生成相关的request对象,以供downloader进行下载 # callback是指定相应的函数类型 except: continue
代码如下:
# 定义指定的处理的信息def parse_stock(self,response): infoDict = { } # 返回的信息是交给itempipeline进行处理的,所以用字典的信息进行存储 stockInfo = response.css('.stock-bets') name = stockInfo.css('.bet-name').extract()[0] keyList= stockInfo.css('dt').extract() valueList = stockInfo.css('dd').extract() for i in range(len(keyList)): key = re.findall(r'>.*',valueList[i])[0] except: val = '--' infoDict[key] = val # 一个字典条目,增加一个股票名称 infoDict['股票名称'] = re.findall('\s.*\(',name)[0].split()[0] + re.findall('\>.*\<',name)[0] yield infoDict # 将生成的item给itemPipeLine进行处理
import scrapyimport reclass StocksSpider(scrapy.Spider): name = 'stocks' start_urls = ['http://quote.eastmoney.com/stocklist.html'] # 是先从东方财富网获得每个股票的代码,然后生成和百度股票相关的url连接 def parse(self, response): for href in response.css('a::attr(href)').extract(): # 提取其中所有的a标签,并获取其中href连接 try: stock = re.findall(r'[s][hz]\d{6}',href)[0] # 通过正则表达式,获得相关的股票的代码 url = 'https://gupiao.baidu.com/stock/' + stock + '.html' # 生成百度股票的html网页 yield scrapy.Request(url,callback=self.parse_stock) # 根据生成的网页在生成相关的request对象,以供downloader进行下载 # callback是指定相应的函数类型 except: continue # 定义指定的处理的信息 def parse_stock(self,response): infoDict = { } # 返回的信息是交给itempipeline进行处理的,所以用字典的信息进行存储 stockInfo = response.css('.stock-bets') name = stockInfo.css('.bet-name').extract()[0] keyList= stockInfo.css('dt').extract() valueList = stockInfo.css('dd').extract() for i in range(len(keyList)): key = re.findall(r'>.*',valueList[i])[0] except: val = '--' infoDict[key] = val # 更新股票的名称 infoDict.update({ '股票名称':re.findall('\s.*\(',name)[0].split()[0] + \ re.findall('\>.*\<',name)[0] }) yield infoDict # 将生成的item给itemPipeLine进行处理
代码如下:
# -*- coding: utf-8 -*-# Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html# 下面的每一个类都是对一个item类进行处理的过程class BaidustocksPipeline: def process_item(self, item, spider): return item# 定义一个专门用来处理的infoDict的方法class BaidustocksInfoPipeline(object): def open_spider(self,spider): self.f = open('BaiduStocksInfo.txt','w') def close_spider(self,spider): self.f.close() # 最核心的,对每一个item的处理方法 def process_item(self,item,spider): try: line = str(dict(item)) + '\n' self.f.write(line) except: pass return item # 如果需要别的函数也可以操作对应的item,就需要返回item对象
这一步千万别忘记,要给系统看的说明书中加上你写的pipeline类
转载地址:http://kggpb.baihongyu.com/