Scrapy框架----- 入门案例

入门案例

学习目标

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

一. 新建项目(scrapy startproject)

  • 在开始爬取以前,必须建立一个新的Scrapy项目。进入自定义的项目目录中,运行下列命令:
scrapy startproject mySpider
  • 其中, mySpider 为项目名称,能够看到将会建立一个 mySpider 文件夹,目录结构大体以下:
  •  

下面来简单介绍一下各个主要文件的做用:html

scrapy.cfg :项目的配置文件python

mySpider/ :项目的Python模块,将会从这里引用代码json

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

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

mySpider/settings.py :项目的设置文件scrapy

mySpider/spiders/ :存储爬虫代码目录ide

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)

爬虫功能要分两步:

1. 爬数据

  • 在当前目录下输入命令,将在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 
其实也能够由咱们自行建立itcast.py并编写上面的代码,只不过使用命令能够免去编写固定代码的麻烦

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

  • name = "" :这个爬虫的识别名称,必须是惟一的,在不一样的爬虫必须定义不一样的名字。

  • allow_domains = [] 是搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页,不存在的URL会被忽略。

  • start_urls = () :爬取的URL元祖/列表。爬虫从这里开始抓取数据,因此,第一次下载的数据将会从这些urls开始。其余子URL将会从这些起始URL中继承性生成。

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

    1. 负责解析返回的网页数据(response.body),提取结构化数据(生成item)
    2. 生成须要下一页的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目录下执行:

scrapy crawl itcast

是的,就是 itcast,看上面代码,它是 ItcastSpider 类的 name 属性,也就是使用 scrapy genspider命令的惟一爬虫名。

运行以后,若是打印的日志出现 [scrapy] INFO: Spider closed (finished),表明执行完成。 以后当前文件夹中就出现了一个 teacher.html 文件,里面就是咱们刚刚要爬取的网页的所有源代码信息。

# 注意,Python2.x默认编码环境是ASCII,当和取回的数据编码格式不一致时,可能会形成乱码; # 咱们能够指定保存内容的编码格式,通常状况下,咱们能够在代码最上方添加: import sys reload(sys) sys.setdefaultencoding("utf-8") # 这三行代码是Python2.x里解决中文编码的万能钥匙,通过这么多年的吐槽后Python3学乖了,默认编码是Unicode了...(祝你们早日拥抱Python3) 

2. 取数据

  • 爬取整个网页完毕,接下来的就是的取过程了,首先观察页面源码:
  •  

<div class="li_txt"> <h3> xxx </h3> <h4> xxxxx </h4> <p> xxxxxxxx </p> 

是否是一目了然?直接上XPath开始提取数据吧。

  • 咱们以前在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 

思考

若是将代码改为下面形式,结果彻底同样。

请思考 yield 在这里的做用:

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) #将获取的数据交给pipelines yield item # 返回数据,不通过pipeline #return items
相关文章
相关标签/搜索