爬虫之Scrapy
Scrapy初步
Scrapy基于Twisted設(shè)計(jì)實(shí)現(xiàn),Twisted的特殊特性是以事件驅(qū)動(dòng),并且對(duì)于異步的支持性很好,集成了高性能的異步下載,隊(duì)列,分布式,持久化等。
Scrapy的安裝
在Linux中可以直接在命令行中輸入:pip install scrapy
在windows中:
- pip3 install wheel
- 下載twisted,http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
- 下載的Twisted一定要和自己當(dāng)前python解釋器的版本相匹配,不然不會(huì)報(bào)這個(gè)錯(cuò)誤:
Twisted-18.9.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.
-?進(jìn)入下載目錄,執(zhí)行 pip3 install Twisted?17.1.0?cp35?cp35m?win_amd64.whl
- pip3 install pywin32
- pip3 install scrapy
Scrapy的目錄結(jié)構(gòu)
使用 scrapy startproject projectname? 啟動(dòng)項(xiàng)目。
- scrapy.cfg scrapy項(xiàng)目的基礎(chǔ)配置
- items.py 設(shè)置數(shù)據(jù)存儲(chǔ)模板,用于結(jié)構(gòu)化數(shù)據(jù),如Django的Model
- middlewares.py 自己定義的中間件
- piplines 數(shù)據(jù)的持久化處理
- settings.py 配置文件,如:遞歸的層數(shù)、并發(fā)數(shù)、延遲下載等
- spiders 爬蟲目錄,創(chuàng)建文件,編寫解析規(guī)則等
創(chuàng)建爬蟲應(yīng)用程序:
- 進(jìn)入項(xiàng)目目錄
- scrapy genspider 應(yīng)用名稱? 爬取網(wǎng)頁(yè)的起始url (例如: scrapy genspider test_1 www.baidu.com)
- 會(huì)出現(xiàn)一個(gè)appname.py的文件,文件內(nèi)容如下
import scrapyclass Test1Spider(scrapy.Spider):name = 'test_1' #應(yīng)用名allowed_domains = ['www.baidu.com'] #允許爬取的域名,如果非該域名的則跳過start_urls = ['http://www.baidu.com/'] #起始爬取的url#訪問起始url并獲取結(jié)果后的回調(diào)函數(shù),該函數(shù)的response參數(shù)就是向起始的url發(fā)送請(qǐng)求后,獲取的相應(yīng)對(duì)象,
該函數(shù)的返回值必須為可迭代對(duì)象獲知NULL
def parse(self, response):pass #response.text 獲取字符串類型的相應(yīng)內(nèi)容
#reponse.body 獲取字節(jié)類型的相應(yīng)內(nèi)容
程序執(zhí)行:
- scrapy crawl? 爬蟲名稱
- scrapy crawl --nolog #不顯示執(zhí)行的日志信息
?
案例一
修改settings.py文件
USER_AGENT="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360EE" ROBOTSTXT_OBEY=False #忽略君子協(xié)議
打開sprider文件
import scrapyclass QiuSprider(scrapy.Sprider):name="qiusp"allowed_domains=['https://www.qiushibaike.com/']start_urls=['https://www.qiushibaike.com/']def parse(self,response):#xpath為response函數(shù)的方法odiv=response.xpath('//div[@id="content-left"]/div')content_list=[] #存儲(chǔ)解析數(shù)據(jù)for div in odiv:#xpath函數(shù)返回列表,列表中的數(shù)據(jù)為selector類型,需要調(diào)用extract()函數(shù)取出數(shù)據(jù)
author = div.xpath('.//div[@class="author clearfix"]/a/h2/text()')[0].extract()
content=div.xpath('.//div[@class="content"]/span/text()')[0].extract()
#將解析內(nèi)容封裝到字典中
dic={ '作者':author, '內(nèi)容':content }
#將數(shù)據(jù)存到content_list中
content_list.append(dic)
return content_list
?
案例二
spider
import scrapyfrom bossPro.items import BossproItem class BossSpider(scrapy.Spider):name = 'boss'# allowed_domains = ['www.xxx.com']start_urls = ['https://www.zhipin.com/job_detail/?query=python%E7%88%AC%E8%99%AB&scity=101010100&industry=&position=']url = 'https://www.zhipin.com/c101010100/?query=python爬蟲&page=%d&ka=page-2'page = 1#解析+管道持久化存儲(chǔ)def parse(self, response):li_list = response.xpath('//div[@class="job-list"]/ul/li')for li in li_list:job_name = li.xpath('.//div[@class="info-primary"]/h3/a/div/text()').extract_first()salary = li.xpath('.//div[@class="info-primary"]/h3/a/span/text()').extract_first()company = li.xpath('.//div[@class="company-text"]/h3/a/text()').extract_first()#實(shí)例化一個(gè)item對(duì)象item = BossproItem()#將解析到的數(shù)據(jù)全部封裝到item對(duì)象中item['job_name'] = job_nameitem['salary'] = salaryitem['company'] = company#將item提交給管道yield itemif self.page <= 3:print('if 執(zhí)行!!!')self.page += 1new_url = format(self.url%self.page)print(new_url)#手動(dòng)請(qǐng)求發(fā)送yield scrapy.Request(url=new_url,callback=self.parse)
items.py
items.py存放的是我們要爬取數(shù)據(jù)的字段信息,我們要爬取的是工作名,薪資,公司名。
# Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass BossproItem(scrapy.Item):# define the fields for your item here like:job_name = scrapy.Field()salary = scrapy.Field()company = scrapy.Field()
pipelines.py
pipelines.py主要是對(duì)spiders中爬蟲返回的數(shù)據(jù)進(jìn)行處理的,在這里我們讓其寫入redis和寫入文件,
pipeline可以隨意定義,但是它是有順序的,所以我們要在settings.py設(shè)置權(quán)重,數(shù)字越小,優(yōu)先級(jí)越高。
# 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.htmlfrom redis import Redis class BossproPipeline(object):fp = Nonedef open_spider(self, spider):print('開始爬蟲......')self.fp = open('./boss.txt','w',encoding='utf-8')def close_spider(self, spider):print('結(jié)束爬蟲......')self.fp.close()#爬蟲文件每向管道提交一次item,則該方法就會(huì)被調(diào)用一次.#參數(shù):item 就是管道接收到的item類型對(duì)象def process_item(self, item, spider):#print(item)self.fp.write(item['job_name']+':'+item['salary']+':'+item['company']+'\n')return item #返回給下一個(gè)即將被執(zhí)行的管道類class redisPileLine(object):conn = Nonedef open_spider(self,spider):self.conn = Redis(host='127.0.0.1',port=6379)print(self.conn)def process_item(self, item, spider):# print(item)dic = {'name':item['job_name'],'salary':item['salary'],'company':item['company']}self.conn.lpush('boss',dic)
settings.py
USER_AGENT="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360EE" ROBOTSTXT_OBEY=False #忽略君子協(xié)議
ITEM_PIPELINES = {'bossPro.pipelines.BossproPipeline': 300,'bossPro.pipelines.redisPileLine': 301, }
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/cuiyuanzhang/p/9493496.html
總結(jié)
- 上一篇: 医院点痣多少钱啊?
- 下一篇: 接口测试(postman jmeter