import os
import uuid
from lxml import html
import aiofiles
import logging
from ruia import Spider, Request
from ruia_ua import middleware
from aiohttp探究.db import MotorBase
import datetime demo = "https://www.mzitu.com/page/{}/" class BaiduImgSpider(Spider):
start_urls = []
img_path = 'data/' async def parse(self, res):
self.mongo_db = MotorBase().get_db('img_data')
source = res.html
root = html.fromstring(source)
url_list = root.xpath("//ul[@id='pins']/li/a/@href")
name_list = root.xpath("//ul[@id='pins']/li/a/img/@alt")
next_page_urls = []
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'max-age=0',
'referer': 'https://www.mzitu.com/mm/',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
}
for each_data in url_list:
next_page_urls.append(each_data)
for name, url in zip(name_list, next_page_urls):
yield Request(url, headers=headers, callback=self.next_page, metadata={"name": name}, res_type='text') async def next_page(self, res):
source = res.html
root = html.fromstring(source)
name = res.metadata.get("name")
refere_url = res.url
# print(name, refere_url)
# 最后一页xpath
max_page_list = "//div[@class='pagenavi']/a[last()-1]/span/text()"
_max_page_num = root.xpath(max_page_list)
max_page_num = _max_page_num[0] if _max_page_num else None
img_url_node = root.xpath("//div[@class='main-image']/p/a/img/@src")
img_url = img_url_node[0] if img_url_node else None
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'max-age=0',
'if-modified-since': 'Thu, 15 Nov 2018 04:24:11 GMT',
'if-none-match': '"5becf4eb-1b7d4"',
'referer': refere_url,
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',
}
datas = []
# yield Request(img_url, callback=self.save_img, headers=headers,
# metadata={"url": img_url, "name": name, "id": "1"},
# res_type='bytes')
data1 = {'url': img_url, "status": "0", 'title': name, "img_id": "1", "headers": headers,
"crawler_date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} datas.append(data1)
# print("最大页数", max_page_num) for page in range(2, int(max_page_num) + 1):
headers["referer"] = f"{refere_url}{str(page).zfill(2)}"
next_img_url = img_url.replace("01.", f"{str(page).zfill(2)}.")
# print("next",next_img_url)
# yield Request(next_img_url, callback=self.save_img, headers=headers,
# metadata={"url": img_url, "name": name, "id": page},
# res_type='bytes')
data2 = {'url': next_img_url, "status": "0", 'title': name, "img_id": page, "headers": headers,
"crawler_date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
datas.append(data2)
await self.mongo_db.mzitu2.insert_many(datas) async def save_img(self, res):
url = res.metadata.get("url")
_img_type = url.rsplit(".", 1)
img_type = _img_type[1] if _img_type else None
name = res.metadata.get("name")
img_id = res.metadata.get("id")
img_all_path = f"{self.img_path}{name}/"
if not os.path.exists(img_all_path):
os.makedirs(img_all_path)
# img_name = str(uuid.uuid1()) + "_" + res.url[-10:].replace('/', '-')
img_name = f"{img_id}.{img_type}"
async with aiofiles.open(img_all_path + img_name, 'wb') as fp:
await fp.write(res.html)
logging.info('Img downloaded successfully in {dir}'.format(dir=img_all_path + img_name)) if __name__ == '__main__':
word = '妹子图' # 目录名
pages = 201 # 页数
BaiduImgSpider.img_path = word + "/"
BaiduImgSpider.start_urls = [demo.format(page) for page in range(pages)]
BaiduImgSpider.start(middleware=middleware)

db.py

import asyncio

from motor.motor_asyncio import AsyncIOMotorClient

class MotorBase:
"""
About motor's doc: https://github.com/mongodb/motor
"""
_db = {}
_collection = {} def __init__(self, loop=None):
self.motor_uri = ''
self.loop = loop or asyncio.get_event_loop() def client(self, db):
# motor
self.motor_uri = f"mongodb://localhost:27017/{db}"
return AsyncIOMotorClient(self.motor_uri, io_loop=self.loop) def get_db(self, db='test'):
"""
Get a db instance
:param db: database name
:return: the motor db instance
"""
if db not in self._db:
self._db[db] = self.client(db)[db] return self._db[db]

福利爬虫妹子图之获取种子url的更多相关文章

  1. 关于如何爬虫妹子图网的源码分析 c#实现

    网上也出现一些抓取妹子图的python 代码,今天我们用c#实现爬虫过程. 请看我的网站: www.di81.com private void www_94xmn_Com(string url, st ...

  2. 爬虫实战【5】送福利!Python获取妹子图上的内容

    [插入图片,妹子图首页] 哈,只敢放到这个地步了. 今天给直男们送点福利,通过今天的代码,可以把你的硬盘装的满满的~ 下面就开始咯! 第一步:如何获取一张图片 假如我们知道某张图片的url,如何获取到 ...

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

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

  4. Python协程爬取妹子图(内有福利,你懂得~)

    项目说明: 1.项目介绍   本项目使用Python提供的协程+scrapy中的选择器的使用(相当好用)实现爬取妹子图的(福利图)图片,这个学会了,某榴什么的.pow(2, 10)是吧! 2.用到的知 ...

  5. Scrapy框架实战-妹子图爬虫

    Scrapy这个成熟的爬虫框架,用起来之后发现并没有想象中的那么难.即便是在一些小型的项目上,用scrapy甚至比用requests.urllib.urllib2更方便,简单,效率也更高.废话不多说, ...

  6. Python爬虫入门教程 2-100 妹子图网站爬取

    妹子图网站爬取---前言 从今天开始就要撸起袖子,直接写Python爬虫了,学习语言最好的办法就是有目的的进行,所以,接下来我将用10+篇的博客,写爬图片这一件事情.希望可以做好. 为了写好爬虫,我们 ...

  7. Python3爬虫系列:理论+实验+爬取妹子图实战

    Github: https://github.com/wangy8961/python3-concurrency-pics-02 ,欢迎star 爬虫系列: (1) 理论 Python3爬虫系列01 ...

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

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

  9. Python Scrapy 爬取煎蛋网妹子图实例(一)

    前面介绍了爬虫框架的一个实例,那个比较简单,这里在介绍一个实例 爬取 煎蛋网 妹子图,遗憾的是 上周煎蛋网还有妹子图了,但是这周妹子图变成了 随手拍, 不过没关系,我们爬图的目的是为了加强实战应用,管 ...

随机推荐

  1. 【BZOJ2424】[HAOI2010]订货(费用流)

    [BZOJ2424][HAOI2010]订货(费用流) 题面 BZOJ 洛谷 题解 傻逼费用流吧... 一开始理解错意思了,仓库大小为\(m\)的含义是留到下个月最多为\(m\),而不是任意时刻的容量 ...

  2. SharePoint 2013 APP 开发示例 (四)JQuery访问REST

    这个示例里,我们将用JQuery AJAX去发送一个 REST请求,并查看返回结果.为了让我们更好地理解REST 接口,我们将添加一个输入框让用户可以指定REST的URL, 这将让我们尝试着用构造的U ...

  3. change username on ubuntu.

    Below tutorial will show you how to change username in ubuntu 12.04 precise.First,we need login as r ...

  4. 【洛谷P1429】平面最近点对

    题解:直接在输入点对的基础上建立 kd-tree,再每次以每个节点的坐标查询离这个点最近的点即可,同时需要忽略这个点本身对该点答案的贡献. 另外,直接在这些点上建立 kd-tree 会比一个一个插入点 ...

  5. 如何在通用权限管理系统中集成log4net日志功能

    开发人员都知道,在系统运行中要记录各种日志,自己写一个日志功能,无论是在效率还是功能扩展上来说都不是很好,目前大多用的是第三方的日志系统,其中一个非常有名,用的最多的就是log4net.下面是关于这个 ...

  6. 有趣的filter

    js中的filter就是过滤的意思,比如,我们以什么样的方式进行过滤,得到我们想要的结果. 对,我们要的就是这个结果. 给定一个数组,我们要的是Burger(汉堡) const restaurants ...

  7. (string高精度)A + B Problem II hdu1002

    A + B Problem II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  8. SQL Server 关于CROSS APPLY 和 OUTER APPLY应用

    先看看语法: <left_table_expression>  {cross|outer} apply<right_table_expression> 再让我们了解一下appl ...

  9. Nginx 入门指南

    Nginx 入门指南 简介: Nginx 是一款轻量级的 Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,其特点是占有内存少,并发能力强.本教程根据淘宝核心系统服务器平台组的 ...

  10. logstash 常用参数

    最近在折腾logstash,其处理流程不过于input.filter.output三个处理流程,以下是我翻译的几个常用的处理参数 output流之http output { http { codec ...