里给出一些 XPath 表达式的例子及对应的含义:
/html/head/title: 选择HTML文档中<head>标签内的<title>元素/html/head/title/text(): 选择上面提到的<title>元素的文字//td: 选择所有的<td>元素//div[@class="mine"]: 选择所有具有class="mine"属性的div元素
举例我们读取网站 http://www.itcast.cn/ 的网站标题,修改 itcast.py 文件代码如下::
# -*- coding: utf-8 -*-import scrapy# 以下三行是在 Python2.x版本中解决乱码问题,Python3.x 版本的可以去掉import sys
reload(sys)sys.setdefaultencoding("utf-8")class Opp2Spider(scrapy.Spider):
name = 'itcast'
allowed_domains = ['itcast.com']
start_urls = ['http://www.itcast.cn/']
def parse(self, response):
# 获取网站标题
context = response.xpath('/html/head/title/text()')
# 提取网站标题
title = context.extract_first()
print(title)
pass执行以下命令:
$ scrapy crawl itcast......传智播客官网-好口碑IT培训机构,一样的教育,不一样的品质......
我们之前在 mySpider/items.py 里定义了一个 ItcastItem 类。 这里引入进来:
from mySpider.items import ItcastItem
然后将我们得到的数据封装到一个 ItcastItem 对象中,可以保存每个老师的属性:
from mySpider.items import ItcastItemdef 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 输出指定格式的文件,命令如下:
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 在这里的作用(Python yield 使用浅析):
# -*- coding: utf-8 -*-import scrapyfrom mySpider.items import ItcastItem# 以下三行是在 Python2.x版本中解决乱码问题,Python3.x 版本的可以去掉import sys
reload(sys)sys.setdefaultencoding("utf-8")class Opp2Spider(scrapy.Spider):
name = 'itcast'
allowed_domains = ['itcast.com']
start_urls = ("http://www.itcast.cn/channel/teacher.shtml",)
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原文链接:https://segmentfault.com/a/1190000013178839

