热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

pythonscrapy爬虫_PythonScrapy爬虫框架实例(一)

之前有介绍scrapy的相关知识,但是没有介绍相关实例,在这里做个小例,供大家参考学习。注:后续不强调python版本&#

之前有介绍 scrapy 的相关知识,但是没有介绍相关实例,在这里做个小例,供大家参考学习。

注:后续不强调python 版本,默认即为python3.x。

爬取目标

这里简单找一个图片网站,获取图片的先关信息。

该网站网址: http://www.58pic.com/c/

创建项目

终端命令行执行以下命令

scrapy startproject AdilCrawler

命令执行后,会生成如下结构的项目。

1213900-20181113115317691-253253420.png

执行结果如下

1213900-20181113123630288-1640368121.png

如上图提示,cd 到项目下,可以执行 scrapy genspider example example.com 命令,创建 名为example,域名为example.com 的 爬虫文件。

编写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

importscrapyclassAdilcrawlerItem(scrapy.Item):#define the fields for your item here like:

#name = scrapy.Field()

author= scrapy.Field() #作者

theme= scrapy.Field() #主题

编写spider文件

进入AdilCrawler目录,使用命令创建一个基础爬虫类:

scrapy genspider thousandPic www.58pic.com#thousandPic为爬虫名,www.58pic.com为爬虫作用范围

执行命令后会在spiders文件夹中创建一个thousandPic.py的文件,现在开始对其编写:

#-*- coding: utf-8 -*-

importscrapy

#爬虫 小试

classThousandpicSpider(scrapy.Spider):

name= 'thousandPic'allowed_domains= ['www.58pic.com']

start_urls= ['http://www.58pic.com/c/']defparse(self, response):'''查看页面元素

/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()

因为页面中 有多张图,而图是以 /html/body/div[4]/div[3]/div[i] 其中i 为变量 作为区分的 ,所以为了获取当前页面所有的图

这里 不写 i 程序会遍历 该 路径下的所有 图片。'''#author 作者

#theme 主题author= response.xpath('/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()').extract()

theme= response.xpath('/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()').extract()#使用 爬虫的log 方法在控制台输出爬取的内容。

self.log(author)

self.log(theme)#使用遍历的方式 打印出 爬取的内容,因为当前一页有20张图片。

for i in range(1, 21):print(i,'****',theme[i - 1], ':',author[i - 1] )

执行命令,查看打印结果

scrapy crawl thousandPic

结果如下,其中DEBUG为 log 输出。

1213900-20181113125629465-1690032349.png

代码优化

引入 item AdilcrawlerItem

#-*- coding: utf-8 -*-

importscrapy#这里使用 import 或是 下面from 的方式都行,关键要看 当前项目在pycharm的打开方式,是否是作为一个项目打开的,建议使用这一种方式。

importAdilCrawler.items as items#使用from 这种方式,AdilCrawler 需要作为一个项目打开。#from AdilCrawler.items import AdilcrawlerItem

classThousandpicSpider(scrapy.Spider):

name= 'thousandPic'allowed_domains= ['www.58pic.com']

start_urls= ['http://www.58pic.com/c/']defparse(self, response):'''查看页面元素

/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()

因为页面中 有多张图,而图是以 /html/body/div[4]/div[3]/div[i] 其中i 为变量 作为区分的 ,所以为了获取当前页面所有的图

这里 不写 i 程序会遍历 该 路径下的所有 图片。'''item=items.AdilcrawlerItem()#author 作者

#theme 主题

author= response.xpath('/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()').extract()

theme= response.xpath('/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()').extract()

item['author'] =author

item['theme'] =themereturn item

再次运营爬虫,执行结果如下

1213900-20181113134020802-448048660.png

保存结果到文件

执行命令如下

scrapy crawl thousandPic -o items.json

会生成如图的文件

1213900-20181113134815419-1924673248.png

再次优化,使用 ItemLoader 功能类

使用itemLoader ,以取代杂乱的extract()和xpath()。

代码如下:

#-*- coding: utf-8 -*-

importscrapyfrom AdilCrawler.items importAdilcrawlerItem#导入 ItemLoader 功能类

from scrapy.loader importItemLoader#optimize 优化#爬虫项目优化

classThousandpicoptimizeSpider(scrapy.Spider):

name= 'thousandPicOptimize'allowed_domains= ['www.58pic.com']

start_urls= ['http://www.58pic.com/c/']defparse(self, response):'''查看页面元素

/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()

因为页面中 有多张图,而图是以 /html/body/div[4]/div[3]/div[i] 其中i 为变量 作为区分的 ,所以为了获取当前页面所有的图

这里 不写 i 程序会遍历 该 路径下的所有 图片。'''

#使用功能类 itemLoader,以取代 看起来杂乱的 extract() 和 xpath() ,优化如下i= ItemLoader(item = AdilcrawlerItem(),response =response )#author 作者

#theme 主题i.add_xpath('author','/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()')

i.add_xpath('theme','/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()')return i.load_item()

编写pipelines文件

默认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

classAdilcrawler1Pipeline(object):defprocess_item(self, item, spider):return item

优化后代码如下

#-*- 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

importjsonclassAdilcrawlerPipeline(object):'''保存item数据'''

def __init__(self):

self.filename= open('thousandPic.json','w')defprocess_item(self, item, spider):#ensure_ascii=False 可以解决 json 文件中 乱码的问题。

text = json.dumps(dict(item), ensure_ascii=False) + ',\n' #这里是一个字典一个字典存储的,后面加个 ',\n' 以便分隔和换行。

self.filename.write(text)returnitemdefclose_spider(self,spider):

self.filename.close()

settings文件设置

修改settings.py配置文件

找到pipelines 配置进行修改

#Configure item pipelines#See https://doc.scrapy.org/en/latest/topics/item-pipeline.html#ITEM_PIPELINES = {#'AdilCrawler.pipelines.AdilcrawlerPipeline': 300,#}

#启动pipeline 必须将其加入到“ITEM_PIPLINES”的配置中#其中根目录是tutorial,pipelines是我的pipeline文件名,TutorialPipeline是类名

ITEM_PIPELINES ={'AdilCrawler.pipelines.AdilcrawlerPipeline': 300,

}#加入后,相当于开启pipeline,此时在执行爬虫,会执行对应的pipelines下的类,并执行该类相关的方法,比如这里上面的保存数据功能。

执行命令

scrapy crawl thousandPicOptimize

执行后生成如下图文件及保存的数据

1213900-20181113142245049-757891948.png

使用CrawlSpider类进行翻页抓取

使用crawl 模板创建一个 CrawlSpider

执行命令如下

scrapy genspider -t crawl thousandPicPaging www.58pic.com

items.py 文件不变,查看 爬虫 thousandPicPaging.py 文件

#-*- coding: utf-8 -*-

importscrapyfrom scrapy.linkextractors importLinkExtractorfrom scrapy.spiders importCrawlSpider, RuleclassThousandpicpagingSpider(CrawlSpider):

name= 'thousandPicPaging'allowed_domains= ['www.58pic.com']

start_urls= ['http://www.58pic.com/']

rules=(

Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),

)defparse_item(self, response):

i={}#i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()

#i['name'] = response.xpath('//div[@id="name"]').extract()

#i['description'] = response.xpath('//div[@id="description"]').extract()

return i

修改后如下

#-*- coding: utf-8 -*-

importscrapy#导入链接规则匹配类,用来提取符合规则的连接

from scrapy.linkextractors importLinkExtractor#导入CrawlSpider类和Rule

from scrapy.spiders importCrawlSpider, RuleimportAdilCrawler.items as itemsclassThousandpicpagingSpider(CrawlSpider):

name= 'thousandPicPaging'allowed_domains= ['www.58pic.com']#修改起始页地址

start_urls = ['http://www.58pic.com/c/']#Response里链接的提取规则,返回的符合匹配规则的链接匹配对象的列表

#http://www.58pic.com/c/1-0-0-03.html 根据翻页连接地址,找到 相应的 正则表达式 1-0-0-03 -> \S-\S-\S-\S\S 而且 这里使用 allow

#不能使用 restrict_xpaths ,使用 他的话,正则将失效

page_link = LinkExtractor(allow='http://www.58pic.com/c/\S-\S-\S-\S\S.html', allow_domains='www.58pic.com')

rules=(#获取这个列表里的链接,依次发送请求,并且继续跟进,调用指定回调函数处理

Rule(page_link, callback='parse_item', follow=True), #注意这里的 ',' 要不会报错

)#加上这个 方法是为了 解决 parse_item() 不能抓取第一页数据的问题 parse_start_url 是 CrawlSpider() 类下的方法,这里重写一下即可

defparse_start_url(self, response):

i=items.AdilcrawlerItem()

author= response.xpath('/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()').extract()

theme= response.xpath('/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()').extract()

i['author'] =author

i['theme'] =themeyieldi#指定的回调函数

defparse_item(self, response):

i=items.AdilcrawlerItem()

author= response.xpath('/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()').extract()

theme= response.xpath('/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()').extract()

i['author'] =author

i['theme'] =themeyield i

再次执行

scrapy crawl thousandPicPaging

查看执行结果,可以看到是有4页的内容

1213900-20181113150334732-2114713703.png

再次优化引入ItemLoader 类

#-*- coding: utf-8 -*-

importscrapy#导入链接规则匹配类,用来提取符合规则的连接

from scrapy.linkextractors importLinkExtractor#导入CrawlSpider类和Rule

from scrapy.loader importItemLoaderfrom scrapy.spiders importCrawlSpider, RuleimportAdilCrawler.items as itemsclassThousandpicpagingopSpider(CrawlSpider):

name= 'thousandPicPagingOp'allowed_domains= ['www.58pic.com']#修改起始页地址

start_urls = ['http://www.58pic.com/c/']#Response里链接的提取规则,返回的符合匹配规则的链接匹配对象的列表

#http://www.58pic.com/c/1-0-0-03.html 根据翻页连接地址,找到 相应的 正则表达式 1-0-0-03 -> \S-\S-\S-\S\S 而且 这里使用 allow

#不能使用 restrict_xpaths ,使用 他的话,正则将失效

page_link = LinkExtractor(allow='http://www.58pic.com/c/\S-\S-\S-\S\S.html', allow_domains='www.58pic.com')

rules=(#获取这个列表里的链接,依次发送请求,并且继续跟进,调用指定回调函数处理

Rule(page_link, callback='parse_item', follow=True), #注意这里的 ',' 要不会报错

)#加上这个 方法是为了 解决 parse_item() 不能抓取第一页数据的问题 parse_start_url 是 CrawlSpider() 类下的方法,这里重写一下即可

defparse_start_url(self, response):

i= ItemLoader(item = items.AdilcrawlerItem(),response =response )

i.add_xpath('author','/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()')

i.add_xpath('theme','/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()')yieldi.load_item()#指定的回调函数

defparse_item(self, response):

i= ItemLoader(item = items.AdilcrawlerItem(),response =response )

i.add_xpath('author','/html/body/div[4]/div[3]/div/a/p[2]/span/span[2]/text()')

i.add_xpath('theme','/html/body/div[4]/div[3]/div/a/p[1]/span[1]/text()')yield i.load_item()

执行结果是一样的。

最后插播一条 在线正则表达式测试 工具的广告,地址: http://tool.oschina.net/regex/

应用如下

1213900-20181113151824562-257417314.png

至此,简单完成了一个网站的简单信息的爬取。后面还会有其他内容的介绍~

如果你要觉得对你有用的话,请不要吝惜你打赏,这将是我无尽的动力,谢谢!



推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文为Codeforces 1294A题目的解析,主要讨论了Collecting Coins整除+不整除问题。文章详细介绍了题目的背景和要求,并给出了解题思路和代码实现。同时提供了在线测评地址和相关参考链接。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
author-avatar
我爱妈妈的家常菜_712
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有