scrapy基础

---恢复内容开始---

scrapy

Scrapy 是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。

1.安装环境

MAC下:

pip install scrapy

Win系统下:

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

2.执行流程

在terminal中输入指令:

创建一个工程:

scrapy startproject first_project

创建爬虫文件:

cd first_project  # 进入工程目录
scrapy genspider first www.xxx.com  # 创建爬虫文件

scrapy genspider 应用名称 爬取网页的起始url (例如:scrapy genspider qiubai www.xxx.com)

执行项目:

scrapy crawl first

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

保存数据

scrapy crawl first -o items.json

生成的具体目录如下

基本配置与实现

1.爬虫文件first.py

# -*- coding: utf-8 -*-
import scrapy

class FirstSpider(scrapy.Spider):
    #爬虫文件的名称
    name = 'first'
#允许的域名,一般情况不写,因为爬取图片等资源时,常用到跨域,这样把域名限制后会出现问题 # allowed_domains = ['www.baidu.com']
#起始的url列表:列表中存放的url都会被scrapy进行自动的请求发送 start_urls = ['https://www.baidu.com/','https://www.sogou.com'] #解析数据,访问起始URL并获取结果后的回调函数,该函数的response参数就是向起始的url发送请求后,获取的响应对象.
   #该函数返回值必须为可迭代对象或者NUll
def parse(self, response): print(response.text) # 获取字节类型的响应内容
print(response.body) # 获取字节类型的相应内容

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

# 设置user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'

# 忽略,不遵守Robots协议
ROBOTSTXT_OBEY = False

# 设置item类的优先级
ITEM_PIPELINES = {
    #300表示的是优先级(数值越小优先级越高)
   'firstBloof.pipelines.QiubaiproPipeline': 200,
   'firstBloof.pipelines.MysqlPipeLine': 301,
   'firstBloof.pipelines.RedisPipeLine': 401,
}

 # 日志类型:INFO DEBUG ERROR
 LOG_LEVEL = 'ERROR'

 数据的持久化存储

示例: 爬取糗百首页中段子的内容和标题

# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem

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

    #终端指令的持久化存储:只可以将parse方法的返回值存储到磁盘文件
    # def parse(self, response):
    #     div_list = response.xpath('//div[@id="content-left"]/div')
    #     all_data = []
    #     for div in div_list:
    #         # author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
    #         author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
    #         content = div.xpath('./a/div/span//text()').extract()
    #         content = ''.join(content)
    #
    #         dic = {
    #             'author':author,
    #             'content':content
    #         }
    #
    #         all_data.append(dic)
    #
    #     return all_data
    #基于管道的持久化存储
    def parse(self, response):
        div_list = response.xpath('//div[@id="content-left"]/div')
        all_data = []
        for div in div_list:
            # author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
            author = div.xpath('./div[1]/a[2]/h2/text()').extract_first()
            content = div.xpath('./a/div/span//text()').extract()
            content = ''.join(content)
            #实例化一个item类型的对象
            item = QiubaiproItem()
            #使用中括号的形式访问item对象中的属性
            item['author'] = author
            item['content'] = content

            #将item提交给管道
            yield item
原文地址:https://www.cnblogs.com/robertx/p/10955728.html