scrapy startproject mySpider
下面来简单介绍一下各个主要文件的做用:html
scrapy.cfg :项目的配置文件python
mySpider/ :项目的Python模块,将会从这里引用代码json
mySpider/items.py :项目的目标文件app
mySpider/pipelines.py :项目的管道文件dom
mySpider/settings.py :项目的设置文件scrapy
mySpider/spiders/ :存储爬虫代码目录ide
咱们打算抓取:http://www.itcast.cn/channel/teacher.shtml 网站里的全部讲师的姓名、职称和我的信息。学习
打开mySpider目录下的items.py网站
Item 定义结构化数据字段,用来保存爬取到的数据,有点像Python中的dict,可是提供了一些额外的保护减小错误。编码
能够经过建立一个 scrapy.Item 类, 而且定义类型为 scrapy.Field的类属性来定义一个Item(能够理解成相似于ORM的映射关系)。
接下来,建立一个ItcastItem 类,和构建item模型(model)。
import scrapy class ItcastItem(scrapy.Item): name = scrapy.Field() level = scrapy.Field() info = scrapy.Field()
爬虫功能要分两步:
mySpider/spider
目录下建立一个名为itcast
的爬虫,并指定爬取域的范围:scrapy genspider itcast "itcast.cn"
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类建立一个子类,并肯定了三个强制的属性 和 一个方法。
name = ""
:这个爬虫的识别名称,必须是惟一的,在不一样的爬虫必须定义不一样的名字。
allow_domains = []
是搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页,不存在的URL会被忽略。
start_urls = ()
:爬取的URL元祖/列表。爬虫从这里开始抓取数据,因此,第一次下载的数据将会从这些urls开始。其余子URL将会从这些起始URL中继承性生成。
parse(self, response)
:解析的方法,每一个初始URL完成下载后将被调用,调用的时候传入从每个URL传回的Response对象来做为惟一参数,主要做用以下:
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
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)
<div class="li_txt"> <h3> xxx </h3> <h4> xxxxx </h4> <p> xxxxxxxx </p>
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
# 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
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