参考:https://segmentfault.com/a/1190000013178839
步骤1:新建项目
进入一个目录,Shift+鼠标右键,在当前目录下打开命令行窗口。
scrapy startproject mySpider
其中, mySpider 为项目名称,可以看到将会创建一个 mySpider 文件夹
我们打算抓取:http://www.itcast.cn/channel/… 网站里的所有讲师的姓名、职称和个人信息。
打开mySpider目录下的items.py文件
创建一个ItcastItem 类,和构建item模型(model)
import scrapy
class ItcastItem(scrapy.Item):
name = scrapy.Field()
level = scrapy.Field()
info = scrapy.Field()
步骤2,执行相关初始化
在当前目录下输入命令,将在mySpider/spider目录下创建一个名为itcast的爬虫,并指定爬取域的范围:
scrapy genspider itcast “itcast.cn”
打开 mySpider/spider目录里的 itcast.py,默认增加了下列代码:
import scrapy
class ItcastSpider(scrapy.Spider):
name = "itcast"#这个爬虫的识别名称,必须是唯一的,在不同的爬虫必须定义不同的名字。
allowed_domains = ["itcast.cn"]#是搜索的域名范围,也就是爬虫的约束区域,规定爬虫只爬取这个域名下的网页,不存在的URL会被忽略。
start_urls = (
'http://www.itcast.cn/',
)#爬取的URL元祖/列表。爬虫从这里开始抓取数据,所以,第一次下载的数据将会从这些urls开始。其他子URL将会从这些起始URL中继承性生成。
#解析的方法,每个初始URL完成下载后将被调用
def parse(self, response):
pass
将start_urls的值修改为需要爬取的第一个url
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
修改parse()方法
def parse(self, response):
filename = "teacher.html"
with open("teacher.html","w",encoding="utf-8") as r:
r.write(response.text)
然后运行一下看看,在mySpider目录下执行:
scrapy crawl itcast
步骤3,取数据
页面源码:
<div class="li_txt">
<h3> xxx </h3>
<h4> xxxxx </h4>
<p> xxxxxxxx </p>
完整程序:
from mySpider.items import ItcastItem#我们之前在mySpider/items.py 里定义了一个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
scrapy保存信息的最简单的方法主要有四种,-o 输出指定格式的文件,命令如下:
scrapy crawl itcast -o teachers.json#json格式,默认为Unicode编码
scrapy crawl itcast -o teachers.jsonl#json lines格式,默认为Unicode编码
scrapy crawl itcast -o teachers.csv#csv 逗号表达式,可用Excel打开
scrapy crawl itcast -o teachers.xml#xml格式
解决存储json格式时存为\uxxx的问题:
在settings.py文件中加
FEED_EXPORT_ENCODING = 'UTF-8'