笔者近段时间写了几个爬虫练练手,就找百度图片入手了
什么是scrapy
Scrapy,Python开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。 Scrapy吸引人的地方在于它是一个框架,任何人都可以根据需求方便的修改。它也提供了多种类型爬虫的基类,如BaseSpider、sitemap爬虫等,最新版本又提供了web2.0爬虫的支持。
目标
爬取 百度图库的美女的图片
image
环境介绍
pycharm
ubuntu
创建项目
scrapy startproject image
scrapy genspider meinv 'HdhCmsTestbaidu测试数据'
url='https://image.baidu测试数据/search/indextn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1552550885640_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%BE%8E%E5%A5%B3'
注意点
要将settings中的robot改为false
分析逻辑
image
image 在源代码中可以看到图片的url是放在js中的,只能用re进行匹配,同时将meimv.py中的allowed_urls 注释。
代码
meinv.py
import?scrapy import?re from?..items?import?ImageItem class?BaiduSpider(scrapy.Spider): ????name?=?'meinv' ????#?allowed_domains?=?['baidu测试数据'] ????start_urls?=?['https://image.baidu测试数据/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1552550885640_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%BE%8E%E5%A5%B3'] ????def?parse(self,?response): ????????html?=?response.text ????????img_urls?=?re.findall(r'"thumbURL":"(.*?)"',html) ????????for?index,img_url?in?enumerate(img_urls): ????????????yield?scrapy.Request(img_url,callback=self.parse_img_url,meta={'num':?index}) ????def?parse_img_url(self,response): ????????item?=?ImageItem() ????????item['index']?=?response.meta['num'] ????????item['content']?=?response.body ????????yield?item
item.py
import?scrapy class?ImageItem(scrapy.Item): ????#?define?the?fields?for?your?item?here?like: ????#?name?=?scrapy.Field() ????content?=?scrapy.Field() ????index?=?scrapy.Field()
pipelines.py
class?ImagePipeline(object): ????def?process_item(self,?item,?spider): ????????with?open('%s.jpg'?%?item['index'],'wb')?as?f: ????????????f.write(item['content']) ????????return?item
settings.py
image 运行? scrapy crawl meinv
成功得到
image
当然这是scrapy的简单使用,强大的scrapy可不止下30张图片,后面继续更新.
···? END? ···
感谢您的关注,毛利期待跟大家共同进步。
长按识别二维码关注