标签:adt extract ref 自己 windows ams string json params
Scrapy是用纯Python实现一个为了爬取网站数据、提取结构性数据而编写的应用框架,用途非常广泛。
框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非常之方便。
Scrapy 使用了 Twisted[‘tw?st?d](其主要对手是Tornado)异步网络框架来处理网络通讯,可以加快我们的下载速度,不用自己去实现异步框架,并且包含了各种中间件接口,可以灵活的完成各种需求。
Scrapy框架官方网址:http://doc.scrapy.org/en/latest
Scrapy中文维护站点:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html
pip install --upgrade pippip install Scrapy
scrapy startproject mySpider

下面来简单介绍一下各个主要文件的作用:
我们打算抓取: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
<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
标签:adt extract ref 自己 windows ams string json params
原文地址:https://www.cnblogs.com/shifu204/p/9663334.html