items的导入
需要Mark Directory as(第一个选项)
item={} 字典
item=SpiderItem()对象
古诗文案例练习
第一步:创建scrapy框架
scrapy startproject gsw
第二步:创建爬虫项目
scrapy genspider gs gs.org
第三步:打开settings中的几个要素
1.LOG_LEVEL = ‘WARNING’ #log等级
2.ROBOTSTXT_OBEY = False #robots协议改为False
3.# 反爬小headers
DEFAULT_REQUEST_HEADERS = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36’,
‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8’,
‘Accept-Language’: ‘en’,
}
4.#爬虫中间件
SPIDER_MIDDLEWARES = {
‘gsw.middlewares.GswSpiderMiddleware’: 543,
}
5.#下载器中间件
DOWNLOADER_MIDDLEWARES = {
‘gsw.middlewares.GswDownloaderMiddleware’: 543,
}
6.#管道
ITEM_PIPELINES = {
‘gsw.pipelines.GswPipeline’: 300,
}
第四步:解析网页结构
#爬取古诗的标题、朝代、作者、内容
1.检查网页是静态还是动态(ajax)加载页面 本页面为静态页面
2.标题://div [@class=“left”]/div[@class=class=“sons”]//p/b/text()
3.作者、朝代 ://div [@class=“left”]/div[@class=“sons”]//p[@class=class=“source”]/a/text()
4.内容://div [@class=“left”]/div[@class=class=“sons”]/div[@class=class=“contson”]//text()
第五步:代码实现
def parse(self, response):
item = GswItem() #将对象进行实列化
div_gsw = response.xpath(’//div[@class=“left”]/div[@class=“sons”]’)
for gsw in div_gsw:
source = gsw.xpath(’.//p[@class=“source”]/a/text()’).extract()
if source:
title = gsw.xpath(’.//p//b/text()’).extract_first()
item[‘title’] = title
author = source[0]
item[‘author’] = author
dynasty = source[1]
item[‘dynasty’] = dynasty
content = gsw.xpath(’.//div[@class=“contson”]/text()’).extract()
#通过join方法给列表每一个字后面都添加一个空格,然后通过strip去掉所有空格
contents = ‘’.join(content).strip()
item[‘contents’] = contents
yield item #将所有装入item的数据返回到管道进行保存
第六步:数据保存
import json
class GswPipeline:
def open_spider(self, spider):
self.f = open(‘gsw.txt’, ‘w’, encoding=‘utf-8’)
def process_item(self, item, spider):
#将item对象转换为python字典,在转换为json类型的字符串
json_item = json.dumps(dict(item), ensure_ascii=False) #ensure_ascii=False
self.f.write(json_item+'\n') #\n换行
return item
def close_spider(self, spider):
self.f.close()
第七步:翻页处理
next_div = response.xpath(’//a[@id=“amore”]/@href’).extract_first() #xpath找地址时不用text()
next_url = response.urljoin(next_div) #response.urljoin()补全地址
yield scrapy.Request(next_url) #翻页进行响应 scrapy.Reques