Scrapy这个成熟的爬虫框架,用起来之后发现并没有想象中的那么难。即便是在一些小型的项目上,用scrapy甚至比用requests、urllib、urllib2更方便,简单,效率也更高。废话不多说,下面详细介绍下如何用scrapy将妹子图爬下来,存储在你的硬盘之中。关于Python、Scrapy的安装以及scrapy的原理这里就不作介绍,自行google、百度了解学习。

一、开发工具
Pycharm 2017
Python 2.7
Scrapy 1.5.0
requests

二、爬取过程

1、创建mzitu项目

进入"E:\Code\PythonSpider>"目录执行scrapy startproject mzitu命令创建一个爬虫项目:

 scrapy startproject mzitu

执行完成后,生产目录文件结果如下:

 ├── mzitu
│   ├── mzitu
│   │   ├── __init__.py
│   │   ├── items.py
│   │   ├── middlewares.py
│   │   ├── pipelines.py
│   │   ├── settings.py
│   │   └── spiders
│   │   ├── __init__.py
│   │   └── Mymzitu.py
│   └── scrapy.cfg

2、进入mzitu项目,编写修改items.py文件

定义titile,用于存储图片目录的名称
定义img,用于存储图片的url
定义name,用于存储图片的名称

 # -*- 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 MzituItem(scrapy.Item):
# define the fields for your item here like:
title = scrapy.Field()
img = scrapy.Field()
name = scrapy.Field()

3、编写修改spiders/Mymzitu.py文件

 # -*- coding: utf-8 -*-
import scrapy
from mzitu.items import MzituItem
from lxml import etree
import requests
import sys
reload(sys)
sys.setdefaultencoding('utf8') class MymzituSpider(scrapy.Spider):
def get_urls():
url = 'http://www.mzitu.com'
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
r = requests.get(url,headers=headers)
html = etree.HTML(r.text)
urls = html.xpath('//*[@id="pins"]/li/a/@href')
return urls name = 'Mymzitu'
allowed_domains = ['www.mzitu.com']
start_urls = get_urls() def parse(self, response):
item = MzituItem()
#item['title'] = response.xpath('//h2[@class="main-title"]/text()')[0].extract()
item['title'] = response.xpath('//h2[@class="main-title"]/text()')[0].extract().split('(')[0]
item['img'] = response.xpath('//div[@class="main-image"]/p/a/img/@src')[0].extract()
item['name'] = response.xpath('//div[@class="main-image"]/p/a/img/@src')[0].extract().split('/')[-1]
yield item next_url = response.xpath('//div[@class="pagenavi"]/a/@href')[-1].extract()
if next_url:
yield scrapy.Request(next_url, callback=self.parse)

我们要爬取的是妹子图网站“最新”的妹子图片,对应的主url是http://www.mzitu.com,通过查看网页源代码发现每一个图片主题的url在<li>标签中,通过上面代码中get_urls函数可以获取,并且返回一个url列表,这里必须说明一下,用python写爬虫,像re、xpath、Beautiful Soup之类的模块必须掌握一个,否则根本无法下手。这里使用xpath工具来获取url地址,在lxml和scrapy中,都支持使用xpath。

     def get_urls():
url = 'http://www.mzitu.com'
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
r = requests.get(url,headers=headers)
html = etree.HTML(r.text)
urls = html.xpath('//*[@id="pins"]/li/a/@href')
return urls

name定义爬虫的名称,allowed_domains定义包含了spider允许爬取的域名(domain)列表(list),start_urls定义了爬取了url列表。

 name = 'Mymzitu'
allowed_domains = ['www.mzitu.com']
start_urls = get_urls()

分析图片详情页,获取图片主题、图片url和图片名称,同时获取下一页,循环爬取:

     def parse(self, response):
item = MzituItem()
#item['title'] = response.xpath('//h2[@class="main-title"]/text()')[0].extract()
item['title'] = response.xpath('//h2[@class="main-title"]/text()')[0].extract().split('(')[0]
item['img'] = response.xpath('//div[@class="main-image"]/p/a/img/@src')[0].extract()
item['name'] = response.xpath('//div[@class="main-image"]/p/a/img/@src')[0].extract().split('/')[-1]
yield item next_url = response.xpath('//div[@class="pagenavi"]/a/@href')[-1].extract()
if next_url:
yield scrapy.Request(next_url, callback=self.parse)

4、编写修改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 requests
import os class MzituPipeline(object):
def process_item(self, item, spider):
headers = {
'Referer': 'http://www.mzitu.com/'
}
local_dir = 'E:\\data\\mzitu\\' + item['title']
local_file = local_dir + '\\' + item['name']
if not os.path.exists(local_dir):
os.makedirs(local_dir)
with open(local_file,'wb') as f:
f.write(requests.get(item['img'],headers=headers).content)
return item

5、middlewares.py文件中新增一个RotateUserAgentMiddleware类

 class RotateUserAgentMiddleware(UserAgentMiddleware):
def __init__(self, user_agent=''):
self.user_agent = user_agent
def process_request(self, request, spider):
ua = random.choice(self.user_agent_list)
if ua:
request.headers.setdefault('User-Agent', ua)
#the default user_agent_list composes chrome,IE,firefox,Mozilla,opera,netscape
#for more user agent strings,you can find it in http://www.useragentstring.com/pages/useragentstring.php
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"
]

6、settings.py设置

 # Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 100
# Disable cookies (enabled by default)
COOKIES_ENABLED = False
DOWNLOADER_MIDDLEWARES = {
'mzitu.middlewares.MzituDownloaderMiddleware': 543,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware':None,
'mzitu.middlewares.RotateUserAgentMiddleware': 400,
}

7、运行爬虫

进入E:\Code\PythonSpider\mzitu目录,运行scrapy crawl Mymzitu命令启动爬虫:

运行结果及完整代码详见:https://github.com/Eivll0m/PythonSpider/tree/master/mzitu

Scrapy框架实战-妹子图爬虫的更多相关文章

  1. 基于Scrapy框架的Python新闻爬虫

    概述 该项目是基于Scrapy框架的Python新闻爬虫,能够爬取网易,搜狐,凤凰和澎湃网站上的新闻,将标题,内容,评论,时间等内容整理并保存到本地 详细 代码下载:http://www.demoda ...

  2. 使用scrapy框架做赶集网爬虫

    使用scrapy框架做赶集网爬虫 一.安装 首先scrapy的安装之前需要安装这个模块:wheel.lxml.Twisted.pywin32,最后在安装scrapy pip install wheel ...

  3. [Python爬虫]煎蛋网OOXX妹子图爬虫(1)——解密图片地址

    之前在鱼C论坛的时候,看到很多人都在用Python写爬虫爬煎蛋网的妹子图,当时我也写过,爬了很多的妹子图片.后来煎蛋网把妹子图的网页改进了,对图片的地址进行了加密,所以论坛里面的人经常有人问怎么请求的 ...

  4. python妹子图爬虫5千张高清大图突破防盗链福利5千张福利高清大图

    meizitu-spider python通用爬虫-绕过防盗链爬取妹子图 这是一只小巧方便,强大的爬虫,由python编写 所需的库有 requests BeautifulSoup os lxml 伪 ...

  5. scrapy框架解读--深入理解爬虫原理

    scrapy框架结构图: 组成部分介绍: Scrapy Engine: 负责组件之间数据的流转,当某个动作发生时触发事件 Scheduler: 接收requests,并把他们入队,以便后续的调度 Do ...

  6. 爬虫入门之Scrapy框架实战(新浪百科豆瓣)(十二)

    一 新浪新闻爬取 1 爬取新浪新闻(全站爬取) 项目搭建与开启 scrapy startproject sina cd sina scrapy genspider mysina http://roll ...

  7. 爬虫 Scrapy框架 爬取图虫图片并下载

    items.py,根据需求确定自己的数据要求 # -*- coding: utf-8 -*- # Define here the models for your scraped items # # S ...

  8. Python网络爬虫 | Scrapy爬取妹子图网站全站照片

    根据现有的知识,写了一个下载妹子图(meizitu.com)Scrapy脚本,把全站两万多张照片下载到了本地. 网站的分析 网页的网址分析 打开网站,发现网页的网址都是以 http://www.mei ...

  9. 基于Scrapy框架的增量式爬虫

    概述 概念:监测 核心技术:去重 基于 redis 的一个去重 适合使用增量式的网站: 基于深度爬取的 对爬取过的页面url进行一个记录(记录表) 基于非深度爬取的 记录表:爬取过的数据对应的数据指纹 ...

随机推荐

  1. css3渐变之线性渐变

    css3定义了两种类型的渐变,即线性渐变和径向渐变.这里我要说的是线性渐变. 为了创建一个线性渐变,你必须至少定义两种颜色结点.颜色结点即你想要呈现平稳过渡的颜色.同时,你也可以设置一个起点和一个方向 ...

  2. 怎么解决dede首页网址自动加上index.html

    怎样去掉dedecms5.7(织梦)首页url后index.html有三种方法 1.去配置你的空间的默认首页地址.把index.html移到默认文本最前面.(确保你的默认文档里面有index.html ...

  3. 全栈开发之HTML快速入门(一)

    一.HTML 是什么? HTML 指的是超文本标记语言 (Hyper Text Markup Language) HTML 不是一种编程语言,而是一种标记语言 (markup language) 标记 ...

  4. PostgreSQL 的 distinct on 的理解

    摘录自:http://www.cnblogs.com/gaojian/archive/2012/09/05/2671381.html 对于 select distinct on , 可以利用下面的例子 ...

  5. jQuery --- 实现 checkbox 样式的单选框

    早就想写点博客了 一直懒着动  最近发现一些写过的东西都不记得了,下决心把自己平时遇到的问题.得到的经验记录下来,希望能大家一点帮助 这是之前写的一个模态框 要求单选 但是 要求radio的默认样式 ...

  6. php等比例压缩图片

    <?php function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) { $pic_width = imagesx($im); ...

  7. Github终于连上了hexo

    2018-01-2722:59:28 我的妈呀,看看这感人的网速,哎不想吐槽在中国连外网的速度 总结一下连接过程吧 漫漫长征路,难的要死. 一.github的注册和使用不再详述 二.Git Desk ...

  8. 转-CSS padding margin border属性详解

    原文链接:http://www.cnblogs.com/linjiqin/p/3556497.html 图解CSS padding.margin.border属性W3C组织建议把所有网页上的对像都放在 ...

  9. Android开发之蓝牙Socket

    蓝牙Server端就是通过线程来注册一个具有名称和唯一识别的UUID号的BluetoothServerSocket, 然后就一直监听Client端(BluetoothSocket)的请求,并对这些请求 ...

  10. remoteViews简介

    RemoteViews从字面上看是一种远程视图.RemoteViews具有View的结构,既然是远程View,那么它就可以在其他进程中显示.由于它可以跨进程显示,所以为了能够更新他的界面,Remote ...