Python爬虫开发【第1篇】【Scrapy入门】

Scrapy的安装介绍

Scrapy框架官方网址:http://doc.scrapy.org/en/latest

Scrapy中文维护站点:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html

Windows 安装方式

  • Python 2 / 3
  • 升级pip版本:pip install --upgrade pip
  • 通过pip 安装 Scrapy 框架pip install Scrapy

具体Scrapy安装流程参考:http://doc.scrapy.org/en/latest/intro/install.html#intro-install-platform-notes

目标

  • 创建一个Scrapy项目
  • 定义提取的结构化数据(Item)
  • 编写爬取网站的 Spider 并提取出结构化数据(Item)
  • 编写 Item Pipelines 来存储提取到的Item(即结构化数据)

1.新建项目(scrapy startproject)

  • 在开始爬取之前,必须创建一个新的Scrapy项目。进入自定义的项目目录中,运行下列命令:
  • scrapy startproject mySpider
  • 创建项目mySpider,目录及主要文件作用:
    • scrapy.cfg :项目的配置文件
    • mySpider/ :项目的Python模块,将会从这里引用代码

    • mySpider/items.py :项目的目标文件

    • mySpider/pipelines.py :项目的管道文件

    • mySpider/settings.py :项目的设置文件mySpider/spiders/ :存储爬虫代码目录

2.明确目标(mySpider/items.py)

目标:抓取http://www.itcast.cn/channel/teacher.shtml 网站里的所有讲师的姓名、职称和个人信息

步骤:

  1. 打开mySpider目录下的items.py

  2. Item 定义结构化数据字段,用来保存爬取到的数据,有点像Python中的dict,但是提供了一些额外的保护减少错误。

  3. 可以通过创建一个 scrapy.Item 类, 并且定义类型为 scrapy.Field的类属性来定义一个Item(可以理解成类似于ORM的映射关系)。

  4. 接下来,创建一个ItcastItem 类,和构建item模型(model)。

import scrapy

class ItcastItem(scrapy.Item):
    name = scrapy.Field()
    level = scrapy.Field()
    info = scrapy.Field()

3.制作爬虫 (spiders/itcastSpider.py)

①.爬数据

 在当前目录下输入命令,将在mySpider/spider目录下创建一个名为itcast的爬虫,并指定爬取域的范围:

scrapy genspider itcast "itcast.cn"  

 打开 mySpider/spider目录里的 itcast.py,默认增加了下列代码:

import scrapy

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

    def parse(self, response):
        pass

要建立一个Spider, 须用scrapy.Spider类创建一个子类,并确定了三个强制的属性 和 一个方法。

  A:name = "" ,爬虫的识别名称,必须是唯一的,在不同的爬虫必须定义不同的名字。

  B:allow_domains = [] ,搜索的域名范围,即爬虫的约束区域,规定爬虫只爬不存在的URL会被忽略。

  C:start_urls = () ,爬取的URL元组/列表。

    爬虫从这里开始抓取数据,所以,第一次下载的数据将会从这些urls开始。其他子URL将会从这些起始URL中继承性生成。

  D:parse(self, response),解析方法,每个初始URL完成下载后将被调用,调用的时候传入从每一个URL传回的Response对象来作为唯一参数,主要作用如下:

    • 负责解析返回的网页数据(response.body),提取结构化数据(生成item)
    • 生成需要下一页的URL请求。
将start_urls的值修改为需要爬取的第一个url
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
修改parse()方法
def parse(self, response):
    filename = "teacher.html"
    open(filename, 'w').write(response.body)
运行程序,即可得到爬取的网页信息

②.取数据

 爬取整个网页完毕,接下来的就是取数据

 观察网页源码样式,选择合适方法提取数据

 将之前在mySpider/items.py 里定义的ItcastItem类引入 :

from mySpider.items import ItcastItem

 将得到的数据封装到一个 ItcastItem 对象中,可以保存每个老师的属性: 

from mySpider.items import ItcastItem

def parse(self, response):
    #open("teacher.html","wb").write(response.body).close()

    # 存放老师信息的集合
    items = []

    for each in response.xpath("//div[@class='li_txt']"):
        # 将我们得到的数据封装到一个 `ItcastItem` 对象
        item = ItcastItem()
        #extract()方法返回的都是unicode字符串
        name = each.xpath("h3/text()").extract()
        title = each.xpath("h4/text()").extract()
        info = each.xpath("p/text()").extract()

        #xpath返回的是包含一个元素的列表
        item['name'] = name[0]
        item['title'] = title[0]
        item['info'] = info[0]

        items.append(item)

    # 直接返回最后数据
    return items

③.保存数据 

scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,,命令如下:
# json格式,默认为Unicode编码
scrapy crawl itcast -o teachers.json

# json lines格式,默认为Unicode编码
scrapy crawl itcast -o teachers.jsonl

# csv 逗号表达式,可用Excel打开
scrapy crawl itcast -o teachers.csv

# xml格式
scrapy crawl itcast -o teachers.xml

  

 

原文地址:https://www.cnblogs.com/loser1949/p/9461882.html