Scrapy 基本使用总结

目录

一、Scrapy框架安装

二、创建Scrapy项目

三、创建爬虫文件

四、运行spider文件

五、各个组件功能

1、spider目录下的文件

2、settIngs.py配置文件

3、持久化存储步骤

六、将数据存入mysql、redis

(1)在管道文件里添加相应的管道类用于持久化存储

(2)配置setting.py里的管道配置

七、手动发起请求


一、Scrapy框架安装

pip install Scrapy

conda install Scrapy

二、创建Scrapy项目

scrapy startproject 项目名

三、创建爬虫文件

进入项目路径:

scrapy genspider 爬虫文件名 爬虫文件的url

创建后会在spider目录下生成,介绍如下:

import scrapy


class ItcastSpider(scrapy.Spider):
    name = 'itcast'  # 爬虫名,爬虫文件的唯一标志
    allowed_domains = ['itcast.cn']  # 允许爬取的范围
     # 最开始请求的url地址,可以为多个,默认会自动发起get请求
    start_urls = ['http://www.itcast.cn/channel/teacher.shtml'] 

    def parse(self, response):
        # response即为响应回的数据
        # 用于请求后的数据解析
        # 处理start_url地址对应的响应
        ret1 = response.xpath("//div[@class='tea_con']//h3/text()")
        print(ret1)

四、运行spider文件

到项目路径下:

scrapy crawl 爬虫文件名(不要后缀)

五、各个组件功能

1、spider目录下的文件

负责数据解析

parse里数据解析时,使用的xpath和etree.xpath有所不同的是返回的对象是selector对象,需要使用extract()方法来获取每条数据。

获取返回的selector对象的数据相应的方法:

方法描述
.extract()解析selector对象后返回数组
.extract_first()和extract()方法类似但返回的是第一条数据

2、settIngs.py配置文件

常用的属性

属性描述
LOG_LEVEL一般为WARNING或ERROR,在该层级以上时才会打印日志,默认打印所有日志。
USER_AGENTUA伪装。
ROBOTSTXT_OBEYrobots协议,一般使用都要禁止,False。
ITEM_PIPELINES开启后便开启了管道类的使用,里面的数字代表优先级,数字越小优先级越高。优先级高的管道类先执行。
CONCURRENT_REQUESTS默认为16,开启请求的线程数
COOKIES_ENABLED开启并为True时,请求当中如果产生了cookie会被自动记录下来到其他请求中
IMAGES_STORE用于存放图片文件下载时的路径
RETRY_ENABLED设置为False表示请求失败时禁止重试
DOWNLOAD_TIMEOUT如设置为10,则表示下载时间超过10秒就不要该条数据了

3、持久化存储步骤

(1)items.py里定义与parse解析好返回相同数量的变量容器

如:

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class Scrapypro01Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # Field()定义的变量当做万能类型的变量
    title = scrapy.Field()
    content = scrapy.Field()

(2)持久化存储前的准备,爬虫解析文件里的parse()方法需返回对应的Item对象

如:

import scrapy
from scrapyPro01.items import Scrapypro01Item


class ItcastSpider(scrapy.Spider):
    name = 'itcast'
    allowed_domains = ['itcast.cn']
    start_urls = ['http://www.itcast.cn/channel/teacher.shtml']

    def parse(self, response):
        title = "title"
        content = "content"

        # 创建items.py里对应的对象,记得先导包
        item = Scrapypro01Item()
        item["title"] = title
        item["content"] = content

        # 将item对象提交给管道
        yield item

(3)利用管道类持久化存储

使用管道类之前需要先开启配置类里的管道类配置,见settings.py的使用

如:

# 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


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class Scrapypro01Pipeline:

    def open_spider(self, spider):
        self.fp = open("test.txt", "w", encoding="utf-8")
        # 该方法只会在爬虫开始时执行一次

    def close_spider(self, spider):
        # 该方法只会在爬虫结束时执行一次
        self.fp.close()

    def process_item(self, item, spider):
        # 该方法用来接收item对象,一次只能接收一个,可以接收多次
        # 参数item就是接收的item对象
        # 写入文件
        self.fp.write(item["title"] + ":" + item["content"] + "\n")
        return item

六、将数据存入mysql、redis

(1)在管道文件里添加相应的管道类用于持久化存储

# 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


# useful for handling different item types with a single interface
import pymysql
from redis import Redis


class Scrapypro01Pipeline:

    def open_spider(self, spider):
        self.fp = open("test.txt", "w", encoding="utf-8")
        # 该方法只会在爬虫开始时执行一次

    def close_spider(self, spider):
        # 该方法只会在爬虫结束时执行一次
        self.fp.close()

    def process_item(self, item, spider):
        # 该方法用来接收item对象,一次只能接收一个,可以接收多次
        # 参数item就是接收的item对象
        # 写入文件
        self.fp.write(item["title"] + ":" + item["content"] + "\n")
        return item


# 将数据存储到mysql中
class MysqlPipLine(object):
    conn = None
    cursor = None

    def open_spider(self, spider):
        self.conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", database="test")
        print(self.conn)

    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        sql = "insert into spider(title,content) values(%s,%s);"

        # 事务处理
        try:
            self.cursor.execute(sql, (item["title"], item["content"]))
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        finally:
            return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()


# 将数据写入redis
class RedisPileLine(object):
    conn = None

    def open_spider(self, spider):
        self.conn = Redis(host="127.0.0.1", port=6379)
        print(self.conn)

    def process_item(self, item, spider):
        self.conn.set("title", item["title"])
        self.conn.set("content", item["content"])

(2)配置setting.py里的管道配置

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'scrapyPro01.pipelines.Scrapypro01Pipeline': 300,
    'scrapyPro01.pipelines.MysqlPipLine': 301,
    'scrapyPro01.pipelines.RedisPileLine': 302,
}

优先级高的可通过process_item里return item将item传递给下一个优先级的item,如果不return则item对象不会再传递给下一个优先级的管道类。

七、手动发起请求

import scrapy
from scrapyPro01.items import Scrapypro01Item


class ItcastSpider(scrapy.Spider):
    name = 'itcast'
    allowed_domains = ['itcast.cn']
    start_urls = ['http://www.itcast.cn/channel/teacher.shtml']

    # 手动发起请求的url
    url = "http://exmaple.cn/%d"
    page_num = 2

    def parse(self, response):
        title = "title"
        content = "content"

        # 创建items.py里对应的对象,记得先导包
        item = Scrapypro01Item()
        item["title"] = title
        item["content"] = content

        # 将item对象提交给管道
        yield item

        # 手动发起GET请求
        if self.page_num < 5:
            new_url = format(self.url % self.page_num)
            yield scrapy.Request(url=new_url, callback=self.parse)  # 回调到本方法进行上面的解析
            # yield scrapy.FormRequest(url=new_url,callback=self.parse,formdata=formdata)#post请求 formata为请求参数
import scrapy
from scrapyPro01.items import Scrapypro01Item


class ItcastSpider(scrapy.Spider):
    name = 'itcast'
    allowed_domains = ['itcast.cn']
    start_urls = ['http://www.itcast.cn/channel/teacher.shtml']

    # 手动发起请求的url
    url = "http://exmaple.cn/%d"
    page_num = 2

    def parse(self, response):
        title = "title"
        content = "content"

        # 创建items.py里对应的对象,记得先导包
        item = Scrapypro01Item()
        item["title"] = title
        item["content"] = content

        # 将item对象提交给管道
        yield item

        # 手动发起GET请求
        if self.page_num < 5:
            new_url = format(self.url % self.page_num)
            yield scrapy.Request(url=new_url, callback=self.parse)  # 回调到本方法进行上面的解析
            # yield scrapy.FormRequest(url=new_url,callback=self.parse,formdata=formdata)#post请求 formata为请求参数

通过yield scrapy.Request手动发起GET请求后回调解析,

yield scrapy.FormRequest手动发起POST请求。

callback到本类中对应的方法。

start_urls实际上是调用了父类的start_requests(self)方法,默认为get请求,如果想让start_urls默认为post请求可以重写该方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值