Scrapy是一个流行的网络爬虫框架,从如今起将陆续记录Python3.6下Scrapy整个学习过程,方便后续补充和学习。
Python网络爬虫之scrapy(一)已经介绍scrapy安装、项目建立和测试基本命令操做,本文将对item设置、提取和使用进行详细说明
item是保存爬取到的数据的容器,其使用方式和字典相似,而且提供了额外保护机制来避免拼写错误致使的未定义字段错误,定义类型为scrapy.Field的类属性来定义一个item,能够根据本身的须要在items.py文件中编辑相应的itemcss
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html #装载咱们抓取数据的容器 import scrapy class ExampleItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field() #属性做为Field对象 population = scrapy.Field()
首先回顾下建立的爬虫模块country.py,继承scrapy.Spider,且定义了三个属性html
name
: 用于区别 Spider。 该名字必须是惟一的,您不能够为不一样的 Spider 设定相同的名字start_urls
: 包含了 Spider 在启动时进行爬取的 url 列表parse()
是 spider 的一个方法。 被调用时,每一个初始 URL 完成下载后生成的 response对象将会做为惟一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成 item)以及生成须要进一步处理的 URL 的 response对象。response经常使用属性:content、text、status_code、cookiesweb
scrapy使用了一种基于xpath和css表达式机制:scrapy selector正则表达式
xpath()
: 传入 xpath 表达式,返回该表达式所对应的全部节点的 selector list 列表css()
: 传入 CSS 表达式,返回该表达式所对应的全部节点的 selector list 列表extract()
: 序列化该节点为 unicode 字符串并返回 listre()
: 根据传入的正则表达式对数据进行提取,返回 unicode 字符串 list 列表scrapy提供了shell命令对网页数据进行抓取shell
命令格式:scrapy shell webapi
D:\Pystu\example>scrapy shell http://example.webscraping.com/places/default/view/Afghanistan-1
>>> response.xpath('//tr//td[@class="w2p_fw"]/text()').extract() ['647,500 square kilometres', '29,121,286', 'AF', 'Afghanistan', 'Kabul', '.af', 'AFN', 'Afghani', '93', 'fa-AF,ps,uz-AF,tk']
class ExampleItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() #属性做为Field对象 population = scrapy.Field(serializer=str)
Field对象这么了每一个字段的元数据(metadata),能够为每一个字段指明任何类型的元数据cookie
item = ExampleItem(name="Afghanistan",population="29121262") print (item)
根据item建立字典网络
>>> dict(ExampleItem) # create a dict from all populated values {"name"="Afghanistan","population"="29121262"}
根据字典建立item框架
>>> Product({"name"="Afghanistan","population"="29121262"}) Product(name="Afghanistan",population="29121262")