当前位置: 首页 > 后端技术 > Python

介绍一个可以替代Scrapy的爬虫框架——feapder

时间:2023-03-26 13:18:37 Python

一、前言众所周知,Python最流行的爬虫框架是Scrapy,主要用于爬取网站结构数据。今天给大家推荐一个更简单、轻量、强大的爬虫框架:feapder2。介绍和安装与Scrapy类似,feapder支持轻量级爬虫、分布式爬虫、批量爬虫、爬虫报警机制等功能。内置三种爬虫如下:AirSpider轻量级爬虫,适合场景简单,数据量小Spider分布式爬虫,基于Redis,适合海量数据,支持断点续爬,数据自动存储等功能.BatchSpider分布式批量爬虫主要用于需要周期性采集的爬虫。实战前,我们先在虚拟环境中安装相应的依赖库#安装依赖库pip3installfeapder3。下面我们使用最简单的AirSpider来爬取一些简单的数据。目标网站:aHR0cHM6Ly90b3BodWIudG9kYXkvIA==详细实现步骤如下(5步)3-1创建爬虫项目首先,我们使用“feapdercreate-p”命令创建爬虫项目#创建爬虫项目feapdercreate-ptophub_demo3-2创建爬虫AirSpider命令行进入spiders文件夹目录,使用“feapdercreate-s”命令创建爬虫cdspiders#创建轻量级爬虫feapdercreate-stophub_spider1其中1为默认,表示要创建轻量级爬虫AirSpider2表示创建分布式爬虫Spider3表示创建分布式批量爬虫BatchSpider3-3配置数据库,创建数据表,创建映射Item以Mysql为例,首先我们在database#创建数据表createtabletopic(idintauto_incrementprimarykey,titlevarchar(100)nullcomment'文章标题',authvarchar(20)nullcomment'作者',like_countintdefault0nullc意见'Likes',collectionintdefault0nullcomment'Favorites',commentintdefault0nullcomment'Comments');然后,打开项目根目录下的settings.py文件,配置数据库连接信息#settings.pyMYSQL_IP="localhost"MYSQL_PORT=3306MYSQL_DB="xag"MYSQL_USER_NAME="root"MYSQL_USER_PASS="root"最后创建一个mappingItem(optional)进入items文件夹,使用“feapdercreate-i”命令创建文件映射到数据库PS:由于AirSpider不支持自动存储数据,所以这一步不是必须的。3-4编写爬虫和数据分析第一步是用“MysqlDB”初始化数据库fromfeapder.db.mysqldbimportMysqlDBclassTophubSpider(feapder.AirSpider):def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)self.db=MysqlDB()第二步,在start_requests方法中,指定要爬取的主链接地址,使用关键字“download_midware”配置随机UAimportfeapderfromfake_useragentimportUserAgentdefstart_requests(self):yieldfeapder.Request("https://tophub.today/",download_midware=self.download_midware)defdownload_midware(self,request):#randomUA#dependency:pip3installfake_useragentua=UserAgent().randomrequest.headers={'User-Agent':ua}returnrequest第三步爬取首页标题和链接地址,使用feapder内置方法xpath解析数据defparse(self,request,response):#print(response.text)card_elements=response.xpath('//div[@class="cc-cd"]')#过滤出对应的卡片元素【什么值得买】buy_good_element=[card_elementforcard_elementincard_elementsifcard_element.xpath('.//div[@class="cc-cd-is"]//span/text()').extract_first()=='什么值得买'][0]#获取内部文章标题和地址a_elements=buy_good_element.xpath('.//div[@class="cc-cd-cbnano"]//a')fora_elementina_elements:#标题和链接title=a_element.xpath('.//span[@class="t"]/text()').extract_first()href=a_element.xpath('.//@href').extract_first()#再次下发新任务以文章标题yieldfeapder.Request(href,download_midware=self.download_midware,callback=self.parser_detail_page,title=title)T第四步,爬取详情页数据。上一步通过key发送了一个新任务callback这个词指定了回调函数,最后在parser_detail_page解析详情页的数据defparser_detail_page(self,request,response):"""解析文章详情数据:paramrequest::paramresponse::return:"""title=request.titleurl=request.url#解析文章详情页,获取点赞数、收藏数、评论数和作者名author=response.xpath('//a[@class="author-title"]/text()').extract_first().strip()print("作者:",author,'文章标题:',title,"地址:",url)desc_elements=response.xpath('//span[@class="xilie"]/span')print("descnumber:",len(desc_elements))#like_count=int(re.findall('\d+',desc_elements[1].xpath('./text()').extract_first())[0])#集合collection_count=int(re.findall('\d+',desc_elements[2].xpath('./text()').extract_first())[0])#评论comment_count=int(re.findall('\d+',desc_elements[3].xpath('./text()').extract_first())[0])print("Like:",like_count,“收藏夹:”,收藏tion_count,"Comment:",comment_count)3-5数据存储使用上面实例化的数据库对象执行SQL,将数据插入数据库#Insertdatabasesql="INSERTINTOtopic(title,auth,like_count,collection,comment)values('%s','%s','%s','%d','%d')"%(title,author,like_count,collection_count,comment_count)#executeself.db.execute(sql)4.最后,最近整理了上百G的Python学习资料,包括新手电子书、教程、源码等,免费分享给大家!想上“Python编程学习圈”,发“J”免费领取