""" 目录结构: project_name/ scrapy.cfg: project_name/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py scrapy.cfg 项目的主配置信息。(真正爬虫相关的配置信息在settings.py文件中) items.py 设置数据存储模板,用于结构化数据,如:Django的Model pipelines 数据持久化处理 settings.py 配置文件,如:递归的层数、并发数,延迟下载等 spiders 爬虫目录,如:建立文件,编写爬虫解析规则 """ #spiders/qiubai.py import scrapy class QiubaiSpider(scrapy.Spider): # 爬虫文件的名称:经过爬虫文件的名称能够指定的定位到某一个具体的爬虫文件 name = 'qiubai' #容许的域名:只能够爬取指定域名下的页面数据(若是遇到非该域名的url则爬取不到数据) #通常不用直接注释了 #allowed_domains = ['https://www.qiushibaike.com/'] #起始url:当前工程将要爬取的页面所对应的url start_urls = ['https://www.qiushibaike.com/'] # 解析方法:访问起始URL并获取结果后的回调函数 # 该函数的response参数就是向起始的url发送请求后,获取的响应对象 # parse方法的返回值必须为可迭代对象或者NUll def parse(self, response): print(response.text) #获取字符串类型的响应内容 print(response.body)#获取字节类型的相应内容 # 建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # xpath为response中的方法,能够将xpath表达式直接做用于该函数中 odiv = response.xpath('//div[@id="content-left"]/div') content_list = [] # 用于存储解析到的数据 for div in odiv: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法能够将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] # xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。 # 咱们解析到的内容被封装在了Selector对象中,须要调用extract()函数将解析的内容从Selecor中取出。 author = div.xpath('.//div[@class="author clearfix"]/a/h2/text()')[0].extract() content = div.xpath('.//div[@class="content"]/span/text()')[0].extract() # author = div.xpath('./div/a[2]/h2/text()').extract_first() # content = div.xpath('.//div[@class="content"]/span/text()').extract_first() # 将解析到的内容封装到字典中 dic = { '做者': author, '内容': content } # 将数据存储到content_list这个列表中 content_list.append(dic) return content_list """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False
""" 基于终端指令 1.保证parse方法返回一个可迭代类型的对象(存储解析到的页面内容) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai -o qiubai.csv --nolog """ # -*- coding: utf-8 -*- import scrapy class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和做者 div_list = response.xpath('//div[@id="content-left"]/div') #存储解析到的页面数据 data_list = [] for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法能够将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() dict = { 'author':author, 'content':content } data_list.append(dict) return data_list """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False
""" 基于管道 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' # allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): # 建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和做者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: # xpath解析到的指定内容被存储到了Selector对象 # extract()该方法能够将Selector对象中存储的数据值拿到 # author = div.xpath('./div/a[2]/h2/text()').extract()[0] # extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() # 1.将解析到的数据值(author和content)存储到items对象 item = QiubaiproItem() item['author'] = author item['content'] = content # 2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class QiubaiproPipeline(object): fp = None # # 构造方法 # def __init__(self): # self.fp = None # 定义一个文件描述符属性 # 整个爬虫过程当中,该方法只会在开始爬虫的时候被调用一次 def open_spider(self, spider): print('开始爬虫') self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8') # 该方法就能够接受爬虫文件中提交过来的item对象,而且对item对象中存储的页面数据进行持久化存储 # 参数:item表示的就是接收到的item对象 # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次 # 由于该方法会被执行调用屡次,因此文件的开启和关闭操做写在了另外两个只会各自执行一次的方法中。 def process_item(self, item, spider): # print('process_item 被调用!!!') # 取出item对象中存储的数据值 author = item['author'] content = item['content'] # 持久化存储 self.fp.write(author + ":" + content + '\n\n\n') return item # 该方法只会在爬虫结束的时候被调用一次 def close_spider(self, spider): print('爬虫结束') self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent # USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipeline': 300, # 300表示为优先级,值越小优先级越高 }
""" 基于mysql的管道存储 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和做者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法能够将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #建立items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql class QiubaiproPipelineByMysql(object): conn = None cursor = None def open_spider(self,spider): print('开始爬虫') #连接数据库 self.conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='123456',db='qiubai') #编写向数据库中存储数据的相关代码 def process_item(self, item, spider): #1.连接数据库 #2.执行sql语句 sql = 'insert into qiubai values("%s","%s")'%(item['author'],item['content']) self.cursor = self.conn.cursor() try: self.cursor.execute(sql) self.conn.commit() except Exception as e: print(e) self.conn.rollback() #3.提交事务 return item def close_spider(self,spider): print('爬虫结束') self.cursor.close() self.conn.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipelineByMysql': 300, #300表示为优先级,值越小优先级越高 }
""" 基于redis的管道存储 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和做者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法能够将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #建立items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import redis class QiubaiproPipelineByRedis(object): conn = None def open_spider(self,spider): print('开始爬虫') self.conn = redis.Redis(host='127.0.0.1',port=6379) def process_item(self, item, spider): dict = { 'author':item['author'], 'content':item['content'] } # 写入redis中 self.conn.lpush('data', dict) return item """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproPipelineByRedis': 300, #300表示为优先级,值越小优先级越高 }
""" 不一样形式的持久化操做 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai --nolog 3.主要就是管道文件pipelines.py和配置文件settings.py -须要在管道文件中编写对应平台的管道类 -在配置文件中对自定义的管道类进行生效操做 """ # -*- coding: utf-8 -*- import scrapy from qiubaiPro.items import QiubaiproItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response): #建议你们使用xpath进行指定内容的解析(框架集成了xpath解析的接口) # 段子的内容和做者 div_list = response.xpath('//div[@id="content-left"]/div') for div in div_list: #xpath解析到的指定内容被存储到了Selector对象 #extract()该方法能够将Selector对象中存储的数据值拿到 #author = div.xpath('./div/a[2]/h2/text()').extract()[0] #extract_first() == extract()[0] author = div.xpath('./div/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #1.将解析到的数据值(author和content)存储到items对象 #建立items对象 item = QiubaiproItem() item['author'] = author item['content'] = content #2.将item对象提交给管道 yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaiproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import redis class QiubaiproByRedis(object): conn = None def open_spider(self,spider): print('开始爬虫') self.conn = redis.Redis(host='127.0.0.1',port=6379) def process_item(self, item, spider): dict = { 'author':item['author'], 'content':item['content'] } # 写入redis中 self.conn.lpush('data', dict) return item class QiubaiproPipeline(object): fp = None # 整个爬虫过程当中,该方法只会在开始爬虫的时候被调用一次 def open_spider(self, spider): print('开始爬虫') self.fp = open('./qiubai_pipe.txt', 'w', encoding='utf-8') # 该方法就能够接受爬虫文件中提交过来的item对象,而且对item对象中存储的页面数据进行持久化存储 # 参数:item表示的就是接收到的item对象 # 每当爬虫文件向管道提交一次item,则该方法就会被执行一次 # 由于该方法会被执行调用屡次,因此文件的开启和关闭操做写在了另外两个只会各自执行一次的方法中。 def process_item(self, item, spider): # print('process_item 被调用!!!') # 取出item对象中存储的数据值 author = item['author'] content = item['content'] # 持久化存储 self.fp.write(author + ":" + content + '\n\n\n') return item # 该方法只会在爬虫结束的时候被调用一次 def close_spider(self, spider): print('爬虫结束') self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False #下列结构为字典,字典中的键值表示的是即将被启用执行的管道文件和其执行的优先级。 ITEM_PIPELINES = { 'qiubaiPro.pipelines.QiubaiproByRedis': 300, #300表示为优先级,值越小优先级越高 'qiubaiPro.pipelines.QiubaiproPipeline': 200, } #上述代码中,字典中的两组键值分别表示会执行管道文件中对应的两个管道类中的process_item方法,实现两种不一样形式的持久化操做。
""" 多个url页面数据爬取 1.对应文件的修改(spiders/qiubai.py,items.py,pipelines.py,settings.py) 2.使用终端指令完成数据存储到制定磁盘文件中的操做 scrapy crawl qiubai --nolog """ # -*- coding: utf-8 -*- import scrapy from qiubaiByPages.items import QiubaibypagesItem class QiubaiSpider(scrapy.Spider): name = 'qiubai' #allowed_domains = ['www.qiushibaike.com/text'] start_urls = ['https://www.qiushibaike.com/text/'] #设计一个通用的url模板 url = 'https://www.qiushibaike.com/text/page/%d/' pageNum = 1 def parse(self, response): div_list = response.xpath('//*[@id="content-left"]/div') for div in div_list: author = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first() content = div.xpath('.//div[@class="content"]/span/text()').extract_first() #建立一个items对象,将解析到数据值存储到items对象中 item = QiubaibypagesItem() item['author'] = author item['content'] = content #将item提交给管道 yield item #请求的手动发送 #13表示的是最后一页的页码 if self.pageNum <= 13: print('爬取到了第%d页的页面数据'%self.pageNum) self.pageNum += 1 new_url = format(self.url % self.pageNum) #callback:将请求获取到的页面数据进行解析 yield scrapy.Request(url=new_url,callback=self.parse) """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class QiubaibypagesItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() author = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class QiubaibypagesPipeline(object): fp = None def open_spider(self,spider): print('开始爬虫') self.fp = open('./qiubai.txt','w',encoding='utf-8') def process_item(self, item, spider): self.fp.write(item['author']+":"+item['content']) return item def close_spider(self,spider): self.fp.close() print('爬虫结束') """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'qiubaiByPages.pipelines.QiubaibypagesPipeline': 300, }
""" post请求发送 """ # -*- coding: utf-8 -*- import scrapy #需求:百度翻译中指定词条对应的翻译结果进行获取 class PostdemoSpider(scrapy.Spider): name = 'postDemo' #allowed_domains = ['www.baidu.com'] start_urls = ['https://fanyi.baidu.com/sug'] #该方法实际上是父类中的一个方法:该方法能够对star_urls列表中的元素进行get请求的发送 #发起post: #1.将Request方法中method参数赋值成post #2.FormRequest()能够发起post请求(推荐) def start_requests(self): print('start_requests()') #post请求的参数 data = { 'kw': 'dog', } for url in self.start_urls: #formdata:请求参数对应的字典 yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse) #发起get: # def start_requests(self): # for u in self.start_urls: # yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): print(response.text)
""" cookie:豆瓣网我的登陆,获取该用户我的主页这个二级页面的页面数据。 """ # -*- coding: utf-8 -*- import scrapy class DoubanSpider(scrapy.Spider): name = 'douban' #allowed_domains = ['www.douban.com'] start_urls = ['https://www.douban.com/accounts/login'] #重写start_requests方法 def start_requests(self): #将请求参数封装到字典 data = { 'source': 'index_nav', 'form_email': '15027900535', 'form_password': 'bobo@15027900535' } for url in self.start_urls: yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse) #针对我的主页页面数据进行解析操做 def parseBySecondPage(self,response): fp = open('second.html', 'w', encoding='utf-8') fp.write(response.text) #能够对当前用户的我的主页页面数据进行指定解析操做 def parse(self, response): #登陆成功后的页面数据进行存储 fp = open('main.html','w',encoding='utf-8') fp.write(response.text) #获取当前用户的我的主页 url = 'https://www.douban.com/people/185687620/' yield scrapy.Request(url=url,callback=self.parseBySecondPage)
""" 代理: 下载中间件做用:拦截请求,能够将请求的ip进行更换。 流程: 1. 下载中间件类的自制定 a) object b) 重写process_request(self,request,spider)的方法 2. 配置文件中进行下载中间件的开启。 """ # -*- coding: utf-8 -*- import scrapy class ProxydemoSpider(scrapy.Spider): name = 'proxyDemo' #allowed_domains = ['www.baidu.com/s?wd=ip'] start_urls = ['https://www.baidu.com/s?wd=ip'] def parse(self, response): fp = open('proxy.html','w',encoding='utf-8') fp.write(response.text) """ middlewares.py """ # -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals #自定义一个下载中间件的类,在类中事先process_request(处理中间价拦截到的请求)方法 class MyProxy(object): def process_request(self,request,spider): #请求ip的更换 request.meta['proxy'] = "https://178.128.90.1:8080" """ settings.py 19行 22行 56行 开启下载中间件 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False DOWNLOADER_MIDDLEWARES = { 'proxyPro.middlewares.MyProxy': 543, }
""" 请求传参 """ # -*- coding: utf-8 -*- import scrapy from moviePro.items import MovieproItem class MovieSpider(scrapy.Spider): name = 'movie' #allowed_domains = ['www.id97.com'] start_urls = ['http://www.id97.com/movie'] #专门用于解析二级子页面中的数据值 def parseBySecondPage(self,response): actor = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[1]/td[2]/a/text()').extract_first() language = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[6]/td[2]/text()').extract_first() longTime = response.xpath('/html/body/div[1]/div/div/div[1]/div[1]/div[2]/table/tbody/tr[8]/td[2]/text()').extract_first() #取出Request方法的meta参数传递过来的字典(response.meta) item = response.meta['item'] item['actor'] = actor item['language'] = language item['longTime'] = longTime #将item提交给管道 yield item def parse(self, response): #名称,类型,导演,语言,片长 div_list = response.xpath('/html/body/div[1]/div[1]/div[2]/div') for div in div_list: name = div.xpath('.//div[@class="meta"]/h1/a/text()').extract_first() #以下xpath方法返回的是一个列表,切列表元素为4 kind = div.xpath('.//div[@class="otherinfo"]//text()').extract() #将kind列表转化成字符串 kind = "".join(kind) url = div.xpath('.//div[@class="meta"]/h1/a/@href').extract_first() print(kind) #建立items对象 item = MovieproItem() item['name'] = name item['kind'] = kind #问题:如何将剩下的电影详情数据存储到item对象(meta) #须要对url发起请求,获取页面数据,进行指定数据解析 #meta参数只能够赋值一个字典(将item对象先封装到字典) yield scrapy.Request(url=url,callback=self.parseBySecondPage,meta={'item':item}) """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class MovieproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name = scrapy.Field() kind = scrapy.Field() actor = scrapy.Field() language = scrapy.Field() longTime = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class MovieproPipeline(object): fp = None def open_spider(self,spider): self.fp = open('movie.txt','w',encoding='utf-8') def process_item(self, item, spider): detail = item['name']+':'+item['kind']+':'+item['actor']+':'+item['language']+':'+item['longTime']+'\n\n\n' self.fp.write(detail) return item def close_spider(self,spider): self.fp.close() """ settings.py 19行 22行 68行 开启管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { 'moviePro.pipelines.MovieproPipeline': 300, }
""" CrawlSpider LinkExtractor:顾名思义,连接提取器。 - 做用:提取response中符合规则的连接。 LinkExtractor( allow=r'Items/',# 知足括号中“正则表达式”的值会被提取,若是为空,则所有匹配。 deny=xxx, # 知足正则表达式的则不会被提取。 restrict_xpaths=xxx, # 知足xpath表达式的值会被提取 restrict_css=xxx, # 知足css表达式的值会被提取 deny_domains=xxx, # 不会被提取的连接的domains。 ) Rule : 规则解析器。根据连接提取器中提取到的连接,根据指定规则提取解析器连接网页中的内容。 Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True) - 参数介绍: 参数1:指定连接提取器 参数2:指定规则解析器解析数据的规则(回调函数) 参数3:是否将连接提取器继续做用到连接提取器提取出的连接网页中。当callback为None,参数3的默认值为true。 rules=( ):指定不一样规则解析器。一个Rule对象表示一种提取规则。 """ # -*- coding: utf-8 -*- import scrapy #导入CrawlSpider相关模块 from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule #表示该爬虫程序是基于CrawlSpider类的 class ChoutiSpider(CrawlSpider): name = 'chouti' #allowed_domains = ['dig.chouti.com'] start_urls = ['https://dig.chouti.com/'] #连接提取器:用来提取指定的连接(url) #allow参数:赋值一个正则表达式 #连接提取器就能够根据正则表达式在页面中提取指定的连接 #提取到的连接会所有交给规则解析器 # 实例化了一个连接提取器对象,且指定其提取规则 link = LinkExtractor(allow=r'/all/hot/recent/\d+') #定义规则解析器,且指定解析规则经过callback回调函数 rules = ( #实例化了一个规则解析器对象 #规则解析器接受了连接提取器发送的连接后,就会对这些连接发起请求,获取连接对应的页面内容,就会根据指定的规则对页面内容中指定的数据值进行解析 #callback:指定一个解析规则(方法/函数) #follow:是否将连接提取器继续做用到链接提取器提取出的连接所表示的页面数据中 Rule(link, callback='parse_item', follow=True), ) #自定义规则解析器的解析规则函数 def parse_item(self, response): print(response) """ settings.py 19行 22行 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False
# -*- coding: utf-8 -*- import scrapy from newsPro.items import NewsproItem from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class Chinanews(CrawlSpider): name = 'chinanews' # allowed_domains = ['http://www.chinanews.com/scroll-news/news1.html'] #中国新闻网(滚动新闻) start_urls = ['http://www.chinanews.com/scroll-news/news1.html', 'http://finance.chinanews.com/cj/gd.shtml' ] custom_settings = { "ITEM_PIPELINES": {'newsPro.pipelines.NewsproPipeline': 300} } link = LinkExtractor(allow=r'http://www.chinanews.com/scroll-news/news\d+.html') link2 = LinkExtractor(allow=r'http://finance.chinanews.com/cj/gd.shtml') # 中国新闻网(财经新闻) rules = ( Rule(link, callback='parse_first', follow=True), Rule(link2, callback='parse_two', follow=True), ) n=0 def parse_first(self, response): li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li') # print(len(li_list)) for li in li_list: url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first() url="http:%s"%url # print(url) yield scrapy.Request(url=url, callback=self.parse_con,) def parse_two(self, response): li_list = response.xpath('/html/body//div[@class="content_list"]/ul/li') # print(len(li_list)) for li in li_list: url = li.xpath('./div[@class="dd_bt"]/a/@href').extract_first() url="http://finance.chinanews.com%s"%url # print(url) yield scrapy.Request(url=url, callback=self.parse_con,) def parse_con(self, response): # self.n+=1 # print(self.n) # print(response) div= response.xpath('/html/body//div[@id="cont_1_1_2"]') title =div.xpath('./h1/text()').extract_first() ctime_s =div.xpath('//div[@class="left-t"]/text()').extract_first().split("来源:") editor =div.xpath('./div[@class="left_name"]/div[@class="left_name"]/text()').extract_first() source =ctime_s[-1] ctime = ctime_s[0] content_list =div.xpath('./div[@class="left_zw"]/p/text()').extract() content = "".join(content_list) # print('=======', title, '=======') # print('=======', ctime,'=======') # print('=======', source, '=======') # print('=======', editor, '=======') # print('=======',content, '=======') item = NewsproItem() item['title'] =title.strip() item['source'] =source.strip() item['content'] =content.strip() item['ctime'] =ctime.strip() item['editor'] =editor.strip() yield item
""" redis实现分布式基本流程 """ # -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from redisPro.items import RedisproItem #导入scrapy-redis中的模块 from scrapy_redis.spiders import RedisCrawlSpider from redisPro.items import RedisproItem class QiubaiSpider(RedisCrawlSpider): name = 'qiubai' #allowed_domains = ['https://www.qiushibaike.com/pic/'] #start_urls = ['https://www.qiushibaike.com/pic/'] #调度器队列的名称 redis_key = 'qiubaispider' #表示跟start_urls含义是同样 #【注意】近期糗事百科更新了糗图板块的反爬机制,更新后该板块的页码连接/pic/page/2/s=5135066, # 末尾的数字每次页面刷新都会变化,所以正则不可写为/pic/page/\d+/s=5135066而应该修改为/pic/page/\d+ link = LinkExtractor(allow=r'/pic/page/\d+') rules = ( Rule(link, callback='parse_item', follow=True), ) def parse_item(self, response): #将图片的url进行解析 div_list = response.xpath('//*[@id="content-left"]/div') for div in div_list: img_url = div.xpath('./div[@class="thumb"]/a/img/@src').extract_first() item = RedisproItem() item['img_url'] = img_url yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class RedisproItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() img_url = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class RedisproPipeline(object): def process_item(self, item, spider): return item """ settings.py 19行 22行 ...管道 ...调度器 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False ITEM_PIPELINES = { #'redisPro.pipelines.RedisproPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, } # 使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 使用scrapy-redis组件本身的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 是否容许暂停 SCHEDULER_PERSIST = True #若是redis服务器不在本身本机,则须要配置redis服务的ip和端口 REDIS_HOST = '172.20.10.7' #redis数据库所在的机器上的ip地址 REDIS_PORT = 6379 #REDIS_PARAMS = {‘password’:’123456’}
""" selenium在scrapy中的应用 from scrapy.http import HtmlResponse #参数介绍: #拦截到响应对象(下载器传递给Spider的响应对象) #request:响应对象对应的请求对象 #response:拦截到的响应对象 #spider:爬虫文件中对应的爬虫类的实例 def process_response(self, request, response, spider): #响应对象中存储页面数据的篡改 if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']: spider.bro.get(url=request.url) js = 'window.scrollTo(0,document.body.scrollHeight)' spider.bro.execute_script(js) time.sleep(2) #必定要给与浏览器必定的缓冲加载数据的时间 #页面数据就是包含了动态加载出来的新闻数据对应的页面数据 page_text = spider.bro.page_source #篡改响应对象 return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request) else: return response """ # -*- coding: utf-8 -*- import scrapy from selenium import webdriver from wangyiPro.items import WangyiproItem from scrapy_redis.spiders import RedisSpider class WangyiSpider(RedisSpider): name = 'wangyi' #allowed_domains = ['www.xxxx.com'] #start_urls = ['https://news.163.com'] redis_key = 'wangyi' def __init__(self): #实例化一个浏览器对象(实例化一次) self.bro = webdriver.Chrome(executable_path='/Users/bobo/Desktop/chromedriver') #必须在整个爬虫结束后,关闭浏览器 def closed(self,spider): print('爬虫结束') self.bro.quit() def parse(self, response): lis = response.xpath('//div[@class="ns_area list"]/ul/li') indexs = [3,4,6,7] li_list = [] #存储的就是国内,国际,军事,航空四个板块对应的li标签对象 for index in indexs: li_list.append(lis[index]) #获取四个板块中的连接和文字标题 for li in li_list: url = li.xpath('./a/@href').extract_first() title = li.xpath('./a/text()').extract_first() #print(url+":"+title) #对每个板块对应的url发起请求,获取页面数据(标题,缩略图,关键字,发布时间,url) yield scrapy.Request(url=url,callback=self.parseSecond,meta={'title':title}) def parseSecond(self,response): div_list = response.xpath('//div[@class="data_row news_article clearfix "]') #print(len(div_list)) for div in div_list: head = div.xpath('.//div[@class="news_title"]/h3/a/text()').extract_first() url = div.xpath('.//div[@class="news_title"]/h3/a/@href').extract_first() imgUrl = div.xpath('./a/img/@src').extract_first() tag = div.xpath('.//div[@class="news_tag"]//text()').extract() tags = [] for t in tag: t = t.strip(' \n \t') tags.append(t) tag = "".join(tags) #获取meta传递过来的数据值title title = response.meta['title'] #实例化item对象,将解析到的数据值存储到item对象中 item = WangyiproItem() item['head'] = head item['url'] = url item['imgUrl'] = imgUrl item['tag'] = tag item['title'] = title #对url发起请求,获取对应页面中存储的新闻内容数据 yield scrapy.Request(url=url,callback=self.getContent,meta={'item':item}) #print(head+":"+url+":"+imgUrl+":"+tag) def getContent(self,response): #获取传递过来的item item = response.meta['item'] #解析当前页面中存储的新闻数据 content_list = response.xpath('//div[@class="post_text"]/p/text()').extract() content = "".join(content_list) item['content'] = content yield item """ items.py """ # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class WangyiproItem(scrapy.Item): # define the fields for your item here like: head = scrapy.Field() url = scrapy.Field() imgUrl = scrapy.Field() tag = scrapy.Field() title = scrapy.Field() content = scrapy.Field() """ pipelines.py """ # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class WangyiproPipeline(object): def process_item(self, item, spider): print(item['title']+':'+item['content']) return item """ middlewares.py """ # -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # https://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals from scrapy.http import HtmlResponse import time from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware import random #UA池代码的编写(单独给UA池封装一个下载中间件的一个类) #1,导包UserAgentMiddlware类 class RandomUserAgent(UserAgentMiddleware): def process_request(self, request, spider): #从列表中随机抽选出一个ua值 ua = random.choice(user_agent_list) #ua值进行当前拦截到请求的ua的写入操做 request.headers.setdefault('User-Agent',ua) #批量对拦截到的请求进行ip更换 class Proxy(object): def process_request(self, request, spider): #对拦截到请求的url进行判断(协议头究竟是http仍是https) #request.url返回值:http://www.xxx.com h = request.url.split(':')[0] #请求的协议头 if h == 'https': ip = random.choice(PROXY_https) request.meta['proxy'] = 'https://'+ip else: ip = random.choice(PROXY_http) request.meta['proxy'] = 'http://' + ip class WangyiproDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None #拦截到响应对象(下载器传递给Spider的响应对象) #request:响应对象对应的请求对象 #response:拦截到的响应对象 #spider:爬虫文件中对应的爬虫类的实例 def process_response(self, request, response, spider): #响应对象中存储页面数据的篡改 if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']: spider.bro.get(url=request.url) js = 'window.scrollTo(0,document.body.scrollHeight)' spider.bro.execute_script(js) time.sleep(2) #必定要给与浏览器必定的缓冲加载数据的时间 #页面数据就是包含了动态加载出来的新闻数据对应的页面数据 page_text = spider.bro.page_source #篡改响应对象 return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request) else: return response PROXY_http = [ '153.180.102.104:80', '195.208.131.189:56055', ] PROXY_https = [ '120.83.49.90:9000', '95.189.112.214:35508', ] user_agent_list = [ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 " "(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 " "(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 " "(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 " "(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 " "(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 " "(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 " "(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 " "(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 " "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 " "(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24" ] """ settings.py 19行 22行 56开启下载中间件 ...管道 """ # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'qiubaiPro (+http://www.yourdomain.com)' USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' # Obey robots.txt rules ROBOTSTXT_OBEY = False DOWNLOADER_MIDDLEWARES = { 'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543, 'wangyiPro.middlewares.RandomUserAgent': 542, 'wangyiPro.middlewares.Proxy': 541, } ITEM_PIPELINES = { #'wangyiPro.pipelines.WangyiproPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, } #配置redis服务的ip和端口 REDIS_HOST = '172.20.10.7' #redis数据库所在的机器上的ip地址 REDIS_PORT = 6379 #REDIS_PARAMS = {‘password’:’123456’} # 使用scrapy-redis组件的去重队列 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # 使用scrapy-redis组件本身的调度器 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 是否容许暂停 SCHEDULER_PERSIST = True