scrapy实战

采用scrapy实现对股票网站的爬取

功能描述:

  技术路线:scrapy

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

实例编写:

  步骤1:建立工程和spider爬虫模板

  步骤2:编写spider

  步骤3:编写item pipeline

新建工程:

生成名为stocks的爬虫

 打开IDE,将项目导入,首先我们要编辑spider文件夹下的stocks.py文件,使其能处理返回的url

import scrapy
import re


class StocksSpider(scrapy.Spider):
    name = 'stocks'
    start_urls = ['http://quote.eastmoney.com/stocklist.html']


    def parse(self, response):
        for href in response.css('a::attr(href)').extract():   #将a标签中的链接进行提取
            try:
                stock = re.findall(r"[s][hz]d{6}", href)[0]   #通过正则表达式库来获取股票代码
                url = 'https://gupiao.baidu.com/stock/' + stock + '.html'
                yield scrapy.Request(url, callback=self.parse_stock)  #给出了处理url的响应函数,定义出一个新的函数parse_stock
            except:
                continue

    def parse_stock(self, response):
        infoDict = {}
        stockInfo = response.css('.stock-bets')    #找到一个属性为stock-bets的区域
        name = stockInfo.css('.bets-name').extract()[0]   #提取股票名字
        keyList = stockInfo.css('dt').extract()           #提取每个dt标签
        valueList = stockInfo.css('dd').extract()         #提取每个dd标签
        for i in range(len(keyList)):                     #遍历每对标签,提取标签的键和值,并存入列表
            key = re.findall(r'>.*</dt>', keyList[i])[0][1:-5]
            try:
                val =re.findall(r'd+.?.*</dd>', valueList[i])[0][1:-5]
            except:
                val = '--'
            infoDict[key] = val

        infoDict.update(
            {'股票名称': re.findall('s.*(', name)[0].split()[0] + re.findall('>.*<', name)[0][1:-1]}
        )       #将页面内股票名称和代码存入列表
        yield infoDict        #以备将列表内的信息传递给ITEM pipeline

接下来要配置pipelines.py文件,定义对爬取项的处理类

class BaidustockPipeline(object):
    def process_item(self, item, spider):
        return item

class BaidustocksInfoPipeline(object):
    def open_spider(self, spider):  #爬虫被调用时,pipeline所启用的方法
        self.f = open('BaiduStockInfo.txt', 'w')

    def close_spider(self, spider): #爬虫关闭时,pipeline所启用的方法
        self.f.close()

    def process_item(self, item, spider):   #将每个股票的信息写入文件中
        try:
            line = str(dict(item)) + '
'
            self.f.write(line)
        except:
            pass
        return item

在pipelines.py中定义了一个类,为了让程序能找到这个类,需要配置ITEM_PIPELINES选项

打开settings.py,找到ITEM_PIPELINES参数,删除注释号

 执行命令:

  

原文地址:https://www.cnblogs.com/Ragd0ll/p/10274572.html