scrapy入门(三)图片爬取和ScrawlSpider

图片懒加载

需要使用未加载图片的伪属性@src2, 在浏览器下滑过程中@src2会自动变成@src

  • 管道类文件
from scrapy.pipeline.images import ImagesPipeline
#自定义管道类
class ImgproPipeline(ImagesPipeline):
	#对媒体资源进行请求
    def get_media_requests(self,item,info):
        yield scrapy.Request(item['img_src'])
    #返回文件名称,不是文件夹路径
	def file_path(self,request,response=None,info=None):
        return request.url.split('/')[-1]
    #将item传递给下一个即将被执行的管道类
    def item_completed(self,results,item,info):
        return item

CrawlSpider

连接提取器 : LinkExtractor

规则解析器 : Rule

使用流程 :

  • 新建工程
  • cd 工程
  • 新建爬虫文件 : scrapy genspider -t crawl spiderName www.xxx.com

源文件设置

#实例化一个链接提取器对象
#作用: 根据指定规则进行链接的提取,并且只提取链接,不会提取符合正则的字符串
#allow后面使用的正则表达式不需要完全匹配,只需要局部匹配即可
link = LinkExtractor(allow=r'type=4&page=d+')
link_detail = LinkExtractor(allow=r'xxxxx')

rules=(
    #将link作用到Rule构造方法的参数中
    #follow = True保证从新的页面提取链接,否则只能提取首页的链接,默认是False
    Rule(link,callback='parse_item',follow=True), 
    Rule(link_detail,callback='parse_detail',follow=False)
    #...
)

def parse_item(self,response):
	#xpath表达式中不能有tbody标签,遇到直接删掉即可
    #如果详情页与首页有共同的唯一标识,可以通过建立两张表,一张是首页的表,一张是详情页的表,然后通过共同的唯一标识将两张表合并. 如果没有相同标识,则需要手动请求和请求传参,不能用Rule请求
	pass
原文地址:https://www.cnblogs.com/yimeisuren/p/12418824.html