""" 目錄結構: 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