scrapy项目创建

安装Scrapy

Scrapy是一个Python第三方模块,执行命令直接安装即可:

pip install scrapy

了解常见命令

scrapy安装好之后,基本使用命令如下:
(venv) e:work_0720venvScripts>scrapy
Scrapy 2.4.0 - no active project
Usage -> 用法:
  scrapy <command> [options] [args]  ->  scrapy 命令 选项 参数
Available commands: -> 有效的操作命令:
  genspider     Generate new spider using pre-defined templates
                使用固定的爬虫架构模板,创建一个爬虫应用
  shell         Interactive scraping console
                在终端进行爬虫测试命令,对目标网站进行测试(爬虫调试时非常有用)
  startproject  Create new project
                使用固定的架构,创建一个爬虫项目(一个爬虫项目中可以包含多个爬虫应用)

  [ more ]      More commands available when run from project directory
   更多命令 ->  更多可以操作的命令,需要在scrapy项目文件夹下才能使用

Scrapy入门

  1. 入门程序
    打开终端,创建一个爬虫项目-> 采集新闻数据
scrapy startproject xinwen
  1. 进入项目,执行命令创建一个爬虫应用-> 采集新浪新闻
cd xinwen
  1. 创建一个名称为sina的爬虫,采集的数据包含在sina.com.cn域名限制下
scrapy genspider sina sina.com.cn
执行完命令之后,会在当前目录中创建一个名称为xinwen的爬虫应用,基本结构如下:
|-- xinwen/                          # xinwen爬虫项目
	|-- xinwen/                           # 项目文件夹
        |-- spiders/                             # 包含具体爬虫应用的目录
            |-- sina.py                              # 项目中一个具体的爬虫应用
        |-- __init__.py                          # 包声明模块
        |-- items.py                             # 封装采集的数据的模块
        |-- middlewares.py                       # 中间件模块,提供拓展功能
        |-- pipelines.py                         # 管道模块
        |-- settings.py                          # 项目配置文件
	|-- scrapy.cfg                        # 项目部署发布配置文件
开发过程中,开发人员需要对爬虫应用进行改造,完成数据的采集:spiders/sina.py
import scrapy                             # 引入模块

class SinaSpider(scrapy.Spider):          # 爬虫应用,需要继承scrapy.Spider类
    name = 'sina'                             # 爬虫名称
    allowed_domains = ['sina.com.cn']     # 采集数据的域名限制
    start_urls = ['https://search.sina.com... =chan..f-8']   # 采集数据URL地址

    def parse(self, response, **kwargs):   # 解析响应数据的函数
        """解析响应数据"""
        # 获取新闻标题
        news = response.xpath("//div[@class='box-result clearfix']/h2/a")
        for title in news:
            print(title)
  1. 启动爬虫,采集数据
scrapy crawl sina
原文地址:https://www.cnblogs.com/duxiangjie/p/13856101.html