Scrapy 安装, 基础使用, 持久化存储

news/2024/7/19 12:30:36 标签: python, 爬虫, json

输入命令

scrapy startproject 项目名称

cd project_name(进入项目目录)

scrapy genspider 应用名称 爬取网页的起始url

scrapy crawl 爬虫名称 / scrapy crawl 爬虫名称 --nolog

 

安装

  Linux:

      pip3 install scrapy

 

  Windows:

      a. pip3 install wheel

      b. 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

      c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl

      d. pip3 install pywin32

      e. pip3 install scrapy

 

 

基础使用

1.创建项目:scrapy startproject 项目名称

  项目结构:

project_name/
   scrapy.cfg:
   project_name/
       __init__.py
       items.py
       pipelines.py
       settings.py
       spiders/
           __init__.py

scrapy.cfg   项目的主配置信息。(真正爬虫相关的配置信息在settings.py文件中)
items.py     设置数据存储模板,用于结构化数据,如:Django的Model
pipelines    数据持久化处理
settings.py  配置文件,如:递归的层数、并发数,延迟下载等
spiders      爬虫目录,如:创建文件,编写爬虫解析规则

2.创建爬虫应用程序:

cd project_name(进入项目目录)
scrapy genspider 应用名称 爬取网页的起始url (例如:scrapy genspider qiubai www.qiushibaike.com)

3.编写爬虫文件:在步骤2执行完毕后,会在项目的spiders中生成一个应用名的py爬虫文件

4.设置修改settings.py配置文件相关配置:

修改内容及其结果如下:
19行:USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' #伪装请求载体身份

22行:ROBOTSTXT_OBEY = False  #可以忽略或者不遵守robots协议

5.执行爬虫程序:scrapy crawl  应用名称

 

class MyspiderSpider(scrapy.Spider):
    name = 'qiubai'
    # allowed_domains = ['www.baidu.com']
    start_urls = ['https://www.qiushibaike.com/text/']

    def parse(self, response):
        lst = response.xpath('//*[@id="content-left"]/div')
        all_data = []
        for el in lst:
            title = el.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = el.xpath('./a[1]/div/span[1]').extract_first()
            all_data.append({'title', title, 'content', content})

        return all_data

 

执行爬虫程序:

scrapy crawl 爬虫名称 :该种执行形式会显示执行的日志信息
scrapy crawl 爬虫名称 --nolog:该种执行形式不会显示执行的日志信息

 

scrapy框架持久化存储

1.基于终端指令的持久化存储

  • 保证爬虫文件的parse方法中有可迭代类型对象(通常为列表or字典)的返回,该返回值可以通过终端指令的形式写入指定格式的文件中进行持久化操作。
执行输出指定格式进行存储:将爬取到的数据写入不同格式的文件中进行存储
    scrapy crawl 爬虫名称 -o xxx.json
    scrapy crawl 爬虫名称 -o xxx.xml
    scrapy crawl 爬虫名称 -o xxx.csv

 

2.基于管道的持久化存储(高效、便捷)

myspider.py

import scrapy
from scrapy1.items import Scrapy1Item

class
MyspiderSpider(scrapy.Spider): name = 'qiubai' # allowed_domains = ['www.baidu.com'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): lst = response.xpath('//*[@id="content-left"]/div') for el in lst: title = el.xpath('./div[1]/a[2]/h2/text()').extract_first() content = el.xpath('./a[1]/div/span[1]').extract_first() item = Scrapy1Item() item['title'] = title item['content'] = content yield item

 

items.py

import scrapy


class Scrapy1Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    content = scrapy.Field()

 

pipelines.py

import pymysql
from redis import Redis
import json


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



class Mypipeline(object):
    def __init__(self):
        self.f = None
    def open_spider(self, spider):
        print('1111111111111111111')
        self.f = open('data.txt', 'w', encoding='utf8')
    def close_spider(self, spider):
        print('2222222222222222222222')
        self.f.close()

    def process_item(self, item, spider):
        self.f.write(item['title'] + '\n' + item['content']+ '\n')
        return item


class Mypipeline_redis(object):
    def __init__(self):
        self.conn = None
        self.cursor =None
    def open_spider(self, spider):
        print('3333333333333333')
        self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='',db='xiubai',charset="utf8")
    def close_spider(self, spider):
        self.conn.close()
        self.cursor.close()
        print('44444444444444444444444')
    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            # print('insert into xiubai values ("%s", "%s")' % (item['title'], item['content']))
            # self.cursor.execute('insert into xiubai values ("%s", "%s")' % (item['title'], item['content']))
            self.cursor.execute('insert into xiubai values ("%s","%s")'%(json.dumps(item['title']), json.dumps(item['content'])))
        except Exception as e:
            print(e)
            self.conn.rollback()
        return item

class Mypipeline_mysql(object):
    def __init__(self):
        self.conn = None

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

    def process_item(self, item, spider):
        dic = {
            'name': item['title'],
            'salary': item['salary'],
        }
        self.conn.lpush('xiubai', json.dumps(dic))
        return item

 

settings.py

BOT_NAME = 'scrapy1'

SPIDER_MODULES = ['scrapy1.spiders']
NEWSPIDER_MODULE = 'scrapy1.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

ITEM_PIPELINES = {
   # 'scrapy1.pipelines.Scrapy1Pipeline': 300,
   #                               301是优先级, 越低优先级越高
   'scrapy1.pipelines.Mypipeline': 301,
   'scrapy1.pipelines.Mypipeline_redis': 302,
   'scrapy1.pipelines.Mypipeline_mysql': 303,
}

 

转载于:https://www.cnblogs.com/NachoLau/p/10463322.html


http://www.niftyadmin.cn/n/987687.html

相关文章

QEMU 4.0.0 发布,几乎可以模拟任何硬件设备的模拟器

QEMU 4.0.0 发布了,此版本更新亮点包括: ARM:实现了一批 ARMv8.X 的扩展,包括 SB、PredInv、HPD、LOR、FHM、AA32HPD、PAuth、JSConv、CondM、FRINT 与 BTIARM:virt:支持 >255 GB 的 RAM 和 u-boot“nol…

asp.net mvc4 controller

controller返回几种返回结果 转载于:https://www.cnblogs.com/wangjunwei/p/3555064.html

Silverlight:Downloader对象详解

这篇是翻译Msdn2上面关于Silverlight的Downloader对象的文章,包括他的属性,方法,事件和Downloading Content on Demand这篇文章!我想很多人都看过这篇文章,但这次我将Downloader对象的所有方法和属性,事件都…

ccnp之vlan间路由加nat地址转换

初次面试的懊悔!本人初次面性质勃勃,朝气庞然有着东方不败的精神,做好一切心里准备在多轮的面试对答过程中没有败阵。我只那为小哥把眼睛一眯,拿出压箱底的问题:如果我公司有两条外网接口分别是A和B双线。下面的交换机…

最优阈值生长算法_结合python与遥感图像的区域生长算法实现

引言本文章将带大家实现灾害监测中一种常用的图像分类方法,即区域生长算法。与前面介绍的几种图像分割方法不同,区域生长算法可直接对高于Uint8灰级的数据直接进行处理,所以保持了原数据的结构形式。另外,区域生长算法涉及到的参数…

组合数学 - 1的个数

1的个数 Mean: 输入一个n,计算小于10^n的正整数中含有1的数的个数。 analyse: 这题是一道组合数学课后思考题。 基本思路: 组合数学乘法原则 容斥原理 n位数中,每位可选:{0,1,2,3,4,5,6,7,8,9},所以共有10^n种,其中…

(Windows)Scala学习1--基础

Scala编程 声明值和变量常量 val,需要事先赋值,不可改变 变量 var 声明变量时,可以不声明类型,例如:val i 1  整型 val i 1.11  浮点型 val i true 布尔型 val i ‘A’ 字符型 val i “Hello World&#…

myeclipse配置下tomcat debug启动很无比慢

myeclipse配置下tomcat debug启动很无比慢,而run启动很快今天照常使用MyEclipse 6.5 Blue Edition进行开发,但是却遇到一个怪问题。在MyEclipse环境下,我习惯每次都用debug模式启动Tomcat。这样不管我需不需要debug,我都能可能用得上debug。奇…