Scrapy各部分运行机制?Xpath为None?多层Response如何编写?搞定
前言Scrapy那么多模块都是怎么结合的啊?明明在chrome上的xpath helper插件写好了xpath,为什么到程序就读取的是None?Scrapy可以直接写多层response么?难道必须再使用requests库?? 没关系,这篇文章一站式解答scrapy常见的坑 Scrapy各部分运行机制
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
网上看到某位大佬生动形象的讲述了如何进行工作,易于理解: Scrapy的运作流程代码写好,程序开始运行...
注意:只有当调度器没有request需要处理时,整个程序才会停止。(对于下载失败的URL,Scrapy也会重新下载。) ? Xpath问题有的网站明明使用了xpath helper插件写好了xpath语句并且chrome验证没问题,但是偏偏到response.xpath的时候就是取不出来值,一直为None,问题出在哪了呢???? 首先我们需要知道,我们在浏览器中看到的html代码可能与从scrapy得到的不一样,所以有时候就会出现在浏览器的xpath无法在程序中使用的问题 解决方法
终极解决方案 scrapy shell 不是说scrapy得到的跟我们在浏览器看到的不同吗?好的,那我们就直接去scrapy得到的响应去看看! 打开命令行,输入命令 scrapy shell url 如百度 ? D:pythonwork>scrapy shell www.baidu.com ? 会发现现在我们进入了scrapy的shell之中 接下来根据提示 输入 view(response) 发现自动开启了浏览器打开了本地的一个网页 没错,这个就是通过scrapy得到的response 直接对于这个网页操作,这下就可以找到适用于我们程序的xpath了 (xpath helper需要在设置中开启允许访问文件网址即本地文件) 肯定有小伙伴发现某些网页403进不去,仔细想想为什么?因为命令行直接进去的是没有用户代理的,一些网站需要我们自己修改user-agent,怎么办? 我们可以在已经编写好各种设置settings的scrapy项目目录下使用scrapy,不然只会使用默认settings ? ? 多层Response的编写我们在使用Scrapy做爬虫的时候经常碰到数据分布在多个页面,要发去多次请求才能收集到足够的信息,例如第一个页面只有简单的几个列表信息,更多的信息在其他request的response中。 而我们一般只写如? ??yield scrapy.Request(next_link,callback=self.parse)? 只是最表层的一页之后就直接回调下一次的运行了,但是如果我们的信息还没有处理完成怎么办?需要更多的request和response处理 该怎么操作呢?总不能再引入使用requests库吧? 解决方案:我在爬取某个壁纸网站的时候遇到了这个问题,首页只得到了各个图片的略缩图,而原图地址需要点开另外的html文件才能获得 解决代码如下: # -*- coding: utf-8 -*- import scrapy from wallpaper.items import WallpaperItem class WallspiderSpider(scrapy.Spider): name = ‘wallspider‘ allowed_domains = [‘wall.alphacoders.com‘] start_urls = [‘https://wall.alphacoders.com/‘] def parse(self,response): picx_list = response.xpath("//div[@class=‘center‘]//div[@class=‘boxgrid‘]/a/@href").getall() for picx in picx_list: url = ‘https://wall.alphacoders.com/‘+str(picx) #回调给下一层处理函数 yield scrapy.Request(url,callback=self.detail_parse) def detail_parse(self,response): pic_url = response.xpath("//*[@id=‘page_container‘]/div[4]/a/@href").get() pic_size = response.xpath("//*[@id=‘wallpaper_info_table‘]/tbody//span/span[2]/a/text()").get() pic_name = response.xpath("//*[@id=‘page_container‘]/div/a[4]/span/text()").get() wall_item = WallpaperItem() wall_item[‘pic_url‘] = pic_url wall_item[‘pic_size‘] = pic_size.split()[0] wall_item[‘pic_name‘] = pic_name print(wall_item) return wall_item 同时我在csdn中看到 名为 kocor的用户写的解决方案则更有教学性,解决方案如下: yield scrapy.Request(item[‘url‘],meta={‘item‘: item},callback=self.detail_parse) Scrapy 用scrapy.Request发起请求可以带上 meta={‘item‘: item} 把之前已收集到的信息传递到新请求里,在新请求里用 item = response.meta(‘item‘) 接受过来,在 item 就可以继续添加新的收集的信息了。 多少级的请求的数据都可以收集。 spider.py文件 # -*- coding: utf-8 -*- import scrapy from Tencent.items import TencentItem class TencentSpider(scrapy.Spider): # 爬虫名称 name = ‘tencent‘ # 允许爬取的域名 allowed_domains = [‘www.xxx.com‘] # 爬虫基础地址 用于爬虫域名的拼接 base_url = ‘https://www.xxx.com/‘ # 爬虫入口爬取地址 start_urls = [‘https://www.xxx.com/position.php‘] # 爬虫爬取页数控制初始值 count = 1 # 爬虫爬取页数 10为只爬取一页 page_end = 1 def parse(self,response): nodeList = response.xpath("//table[@class=‘tablelist‘]/tr[@class=‘odd‘] | //table[@class=‘tablelist‘]/tr[@class=‘even‘]") for node in nodeList: item = TencentItem() item[‘title‘] = node.xpath("./td[1]/a/text()").extract()[0] if len(node.xpath("./td[2]/text()")): item[‘position‘] = node.xpath("./td[2]/text()").extract()[0] else: item[‘position‘] = ‘‘ item[‘num‘] = node.xpath("./td[3]/text()").extract()[0] item[‘address‘] = node.xpath("./td[4]/text()").extract()[0] item[‘time‘] = node.xpath("./td[5]/text()").extract()[0] item[‘url‘] = self.base_url + node.xpath("./td[1]/a/@href").extract()[0] # 根据内页地址爬取 yield scrapy.Request(item[‘url‘],callback=self.detail_parse) # 有下级页面爬取 注释掉数据返回 # yield item # 循环爬取翻页 nextPage = response.xpath("//a[@id=‘next‘]/@href").extract()[0] # 爬取页数控制及末页控制 if self.count < self.page_end and nextPage != ‘javascript:;‘: if nextPage is not None: # 爬取页数控制值自增 self.count = self.count + 1 # 翻页请求 yield scrapy.Request(self.base_url + nextPage,callback=self.parse) else: # 爬虫结束 return None def detail_parse(self,response): # 接收上级已爬取的数据 item = response.meta[‘item‘] #一级内页数据提取 item[‘zhize‘] = response.xpath("//*[@id=‘position_detail‘]/div/table/tr[3]/td/ul[1]").xpath(‘string(.)‘).extract()[0] item[‘yaoqiu‘] = response.xpath("//*[@id=‘position_detail‘]/div/table/tr[4]/td/ul[1]").xpath(‘string(.)‘).extract()[0] # 二级内页地址爬取 yield scrapy.Request(item[‘url‘] + "&123",callback=self.detail_parse2) # 有下级页面爬取 注释掉数据返回 # return item def detail_parse2(self,response): # 接收上级已爬取的数据 item = response.meta[‘item‘] # 二级内页数据提取 item[‘test‘] = "222222222222222111" # 最终返回数据给爬虫引擎 return item 他的文章地址:https://blog.csdn.net/ygc123189/article/details/79160146 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |