爬虫实战----scrapy

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中。其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。

          

scrapy爬虫的使用步骤                                                   scrapy爬虫的数据类型

      1.创建一个工程和Spider模板                                     Request类

      2.编写Spider                                                         Response类

      3.编写Item Pipeline                                                Item类

      4.优化配置策略

实例:

目标: 获取上交所和深交所所有股票的名称和交易信息。
输出: 保存到文件中。
技术路线:Scrapy爬虫框架
语言: python3.6

由于在上一篇博客中已经介绍了股票信息爬取的原理,在这里不再进行过多介绍,如需了解可以参考博客:点击打开链接,在本篇文章中主要讲解该项目在Scrapy框架中如何实现。

我们主要进行两步操作:
(1) 首先需要在框架中编写一个爬虫程序spider,用于链接爬取和页面解析;
(2) 编写pipelines,用于处理解析后的股票数据并将这些数据存储到文件中。

代码编写

步骤:
(1) 建立一个工程生成Spider模板

打开cmd命令行,定位到项目所放的路径,输入:scrapy startproject BaiduStocks,此时会在目录中新建一个名字为BaiduStocks的工程。再输入:cd BaiduStocks进入目录,接着输入:scrapy genspider stocks baidu.com生成一个爬虫。之后我们可以在spiders/目录下看到一个stocks.py文件,如下图所示:


(2) 编写Spider:配置stocks.py文件,修改返回页面的处理,修改对新增URL爬取请求的处理

打开stocks.py文件,代码如下所示:

import scrapy


class StocksSpider(scrapy.Spider):
    name = 'stocks'
    allowed_domains = ['baidu.com']
    start_urls = ['http://baidu.com/']

    def parse(self, response):
        pass
将上述代码修改为

import scrapy
import re
import random
from scrapy.http.response.html import HtmlResponse
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():
            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)
            except:
                continue
    def parse_stock(self,responese):
        infoDict={}
        stockInfo=responese.css('.stock-bets').extract()[0]
        name=stockInfo.css('.stock-bets .bets-name').extract()[0]
        keyList=stockInfo.css('.stock-bets dt').extract()
        valueList=stockInfo.css('.stock-bets dd').extract()
        for i in range(len(keyList)):
            key=re.findall(r'>.*</dt>',keyList[i])[0][1:-5]
            try:
             value=re.findall(r'\d+\.?.*</dd>',valueList[i])[0][1:-5]
            except:
                value='--'
            infoDict[key]=value
        infoDict.update({'股票名称':re.findall('\s.*\(',name)[0].split()[0]+\
                re.findall('\>.*\<',name)[0][1:-1]})
        yield infoDict

(3) 配置pipelines.py文件,定义爬取项(Scraped Item)的处理类

打开pipelinse.py文件,如下图所示:

# 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.html


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

将上述代码修改如下

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


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

class BaidustocksInfoPipeline(object):
    def open_spider(self,spider):
        self.f=open('BaiduStocksInfo.txt','w',encoding='utf-8')
    def close_spider(self,spider):
        self.f.close()
    def  process_item(self,item,spider):
        try:
            line=str(dict(item))+'\n'
            self.f.write(line)
        except:
            pass
        return item
4) 修改settings.py,是框架找到我们在pipelinse.py中写的类

settings.py中加入:

# -*- coding: utf-8 -*-
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'BaiduStocks.pipelines.BaidustocksInfoPipeline': 300,
}
(4) 执行程序
在命令行中输入: scrapy crawl stocks
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值