Python-爬取妹子图(单线程和多线程版本)
一、参考文章
上述文章中的代码讲述的非常清楚,我的基本能思路也是这样,本篇文章中的代码仅仅做了一些异常处理和一些日志显示优化工作,写此文章主要是当做笔记,方便以后查阅,修改的地方如下:
1、异常处理下面在代码中会单独标红
2、多线程版使用了multiprocessing这个库,需要在main函数开始调用freeze_support(),防止打包成exe之后,运行时创建线程失败
3、多线程版本加了一个命令行自定义线程个数功能
二、单线程版本
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import os all_url = 'http://www.mzitu.com' #http请求头
Hostreferer = {
'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Referer':'http://www.mzitu.com'
}
Picreferer = {
'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Referer':'http://i.meizitu.net'
}
#此请求头破解盗链 start_html = requests.get(all_url, headers = Hostreferer) #保存地址
path = os.getcwd() + '/mzitu/' #找寻最大页数
soup = BeautifulSoup(start_html.text, "html.parser")
page = soup.find_all('a', class_='page-numbers')
max_page = page[-2].text same_url = 'http://www.mzitu.com/page/'
for n in range(0, int(max_page)+1):#遍历页面数
ul = same_url+str(n)
start_html = requests.get(ul, headers = Hostreferer)
soup = BeautifulSoup(start_html.text, "html.parser")
all_a = soup.find('div', class_ = 'postlist').find_all('a', target = '_blank')
for a in all_a:#每个页面包含的妹子数
title = a.get_text() #提取文本
if(title != ''):
print("准备扒取:" + title) #win不能创建带?的目录
if(os.path.exists(path+title.strip().replace('?', ''))):
#print('目录已存在')
flag = 1
else:
os.makedirs(path+title.strip().replace('?', ''))
flag = 0
os.chdir(path + title.strip().replace('?', ''))
href = a['href']
html = requests.get(href, headers = Hostreferer)
mess = BeautifulSoup(html.text, "html.parser")
pic_max = mess.find_all('span')
pic_max = pic_max[10].text #最大页数
if(flag == 1 and len(os.listdir(path+title.strip().replace('?', ''))) >= int(pic_max)):
print('已经保存完毕,跳过')
continue
for num in range(1, int(pic_max) + 1):#每个妹子的所有照片
pic = href+'/'+str(num)
html = requests.get(pic, headers = Hostreferer)
mess = BeautifulSoup(html.text, "html.parser")
pic_url = mess.find('img', alt = title) if 'src' not in pic_url.attrs:#有些pic_url标签没有src这个属性,导致操作异常,在次进行过滤
continue
print(pic_url['src'])
#exit(0)
html = requests.get(pic_url['src'],headers = Picreferer)
file_name = pic_url['src'].split(r'/')[-1]
f = open(file_name, 'wb')
f.write(html.content)
f.close()
print('完成')
print('第',n,'页完成')
三、多线程版本
#coding=utf-8
import requests
from bs4 import BeautifulSoup
import os
from multiprocessing import Pool
from multiprocessing import freeze_support
import sys header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.2107.204 Safari/537.36',
'Referer':'http://www.mzitu.com'
}
Picreferer = {
'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
'Referer':'http://i.meizitu.net'
} def find_MaxPage():
all_url = 'http://www.mzitu.com'
start_html = requests.get(all_url, headers = header)
#找寻最大妹子页面数
soup = BeautifulSoup(start_html.text, "html.parser")
page = soup.find_all('a', class_ = 'page-numbers')
max_page = page[-2].text
return max_page def Download(href, title, path):
html = requests.get(href, headers = header)
soup = BeautifulSoup(html.text, 'html.parser')
pic_max = soup.find_all('span')
pic_max = pic_max[10].text # 最大页数
if(os.path.exists(path+title.strip().replace('?', ''))
and len(os.listdir(path+title.strip().replace('?', ''))) >= int(pic_max)):
print('妹子已待命,继续准备下一个妹子' + title)
return 1
print(f"发现妹子资源{pic_max}个,准备中:" + title)
os.makedirs(path + title.strip().replace('?', ''))
os.chdir(path + title.strip().replace('?', ''))
for num in range(1, int(pic_max) + 1):
pic = href + '/' + str(num)
html = requests.get(pic, headers = header)
mess = BeautifulSoup(html.text, "html.parser")
pic_url = mess.find('img', alt = title)
if 'src' not in pic_url.attrs:#有些pic_url标签没有src属性,导致操作异常,在次进行过滤
continue
print(f"{title}:{pic_url['src']}")
html = requests.get(pic_url['src'], headers = header)
file_name = pic_url['src'].split(r'/')[-1]
f = open(file_name,'wb')
f.write(html.content)
f.close()
print('妹子已就绪,客官请慢用:' + title) if __name__ == '__main__':
freeze_support()#防止打包后 运行exe创建进程失败 #线程池中线程数
count = 1
if len(sys.argv) >=2:
count = int(sys.argv[1]) pool = Pool(count)
print(f'初始化下载线程个数${count}') # http请求头
path = os.getcwd() + '/mzitu_mutil/'
max_page = find_MaxPage() #获取最大页数 即生成的文件夹数量
print(f'捕获{max_page}页妹子,请耐心等待下载完成')
same_url = 'http://www.mzitu.com/page/' for n in range(1, int(max_page) + 1):
each_url = same_url + str(n)
start_html = requests.get(each_url, headers = header)#请求一页中的所有妹子
soup = BeautifulSoup(start_html.text, "html.parser")
all_a = soup.find('div', class_ = 'postlist').find_all('a', target = '_blank')
for a in all_a:#遍历每一页中的妹子
title = a.get_text() # 提取文本
if (title != ''):
href = a['href']#请求妹子的所有图集
pool.apply_async(Download, args = (href, title, path))
pool.close()
pool.join()
print('所有妹子已就绪,客官请慢用')
四、资源下载
资源下载地址:Python爬取妹子图-单线程和多线程版本
转载声明:本站文章无特别说明,皆为原创,版权所有,转载请注明:朝十晚八
Python-爬取妹子图(单线程和多线程版本)的更多相关文章
- python爬取妹子图全站全部图片-可自行添加-线程-进程爬取,图片去重
from bs4 import BeautifulSoupimport sys,os,requests,pymongo,timefrom lxml import etreedef get_fenlei ...
- Python 爬取 妹子图(技术是无罪的)
... #!/usr/bin/env python import urllib.request from bs4 import BeautifulSoup def crawl(url): header ...
- Python 爬取妹子图(技术是无罪的)
... import requests from bs4 import BeautifulSoup import os import sys class mzitu(): def html(self, ...
- Python协程爬取妹子图(内有福利,你懂得~)
项目说明: 1.项目介绍 本项目使用Python提供的协程+scrapy中的选择器的使用(相当好用)实现爬取妹子图的(福利图)图片,这个学会了,某榴什么的.pow(2, 10)是吧! 2.用到的知 ...
- Python3爬虫系列:理论+实验+爬取妹子图实战
Github: https://github.com/wangy8961/python3-concurrency-pics-02 ,欢迎star 爬虫系列: (1) 理论 Python3爬虫系列01 ...
- python 爬取妹子
爬取妹子图片 网址:https://www.mzitu.com/jiepai/ 2019-06-13 环境WIN10 1903 python 3.7.3 个人习惯先在IDLE中进行调试 import ...
- Python网络爬虫 | Scrapy爬取妹子图网站全站照片
根据现有的知识,写了一个下载妹子图(meizitu.com)Scrapy脚本,把全站两万多张照片下载到了本地. 网站的分析 网页的网址分析 打开网站,发现网页的网址都是以 http://www.mei ...
- python爬取斗图网中的 “最新套图”和“最新表情”
1.分析斗图网 斗图网地址:http://www.doutula.com 网站的顶部有这两个部分: 先分析“最新套图” 发现地址栏变成了这个链接,我们在点击第二页 可见,每一页的地址栏只有后面的pag ...
- Python爬取 斗图表情,让你成为斗图大佬
话不多说,上结果(只爬了10页内容) 上代码:(可直接运行) 用到Xpath #encoding:utf-8 # __author__ = 'donghao' # __time__ = 2018/ ...
随机推荐
- SpringCloud实战-Ribbon客户端负载均衡
前面我们已经完成了注册中心和服务提供者两个基础组件.接着介绍使用Spring Cloud Ribbon在客户端负载均衡的调用服务. ribbon 是一个客户端负载均衡器,可以简单的理解成类似于 ngi ...
- C#本质论笔记
第一章 C#概述 1.1 Helo,World 学习一种新语言最好的办法就是动手写程序. C#编译器创建的.exe程序是一个程序集(Assembly),我们也可以创建能由另一个较大的程序 ...
- 类设计:设计卖车的4S店
class Car(object): # 定义车的方法 def move(self): print('---车在移动---') def stop(self): print('---停车---') # ...
- Lua读取CSV文件到table中
创建Lua函数载入CSV文件并保存到表中的函数: function GetLines(fileName) indx = 0 myLines ={} for line in io.line(string ...
- python logging method 02
基本用法 下面的代码展示了logging最基本的用法. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
- 3d轮播图——类似酷狗的轮播
说到轮播图,其实只要是跟web开发相关的无论是前端后端应该都不陌生,各种各样的轮播图,从以前的单纯的平面山水画遮盖滑动或滚动,到Jquery的animate甚至是h5+css3,各种炫酷的轮播图更是层 ...
- (十分钟视频教程)nodejs基础实战教程3:react服务端渲染入门篇
视频截图如下: (具体视频见文末) 前言: 这是小猫的第三篇node教程,本篇内容是由公众号粉丝票选得出的,相信大家对这篇教程是抱有较大希望的,这篇教程由小猫和一位多年的好朋友合作完成(笔名:谷雨,博 ...
- Spring Boot实战笔记(五)-- Spring高级话题(Spring Aware)
一.Spring Aware Spring 依赖注入的最大亮点就是你所有的 Bean 对 Spring容器的存在是没有意识的.即你可以将你的容器替换成其他的容器,如Google Guice,这时 Be ...
- css3D的魅力
前言: 最近玩了玩用css来构建3D效果,写了几个demo,所以博客总结一下. 在阅读这篇博客之前,请先自行了解一下css 3D的属性,例如:transform-style,transform-or ...
- C#中的is和as
is检查一个对象是否兼容于指定的类型,不返回Boolean值.注意is操作符永远不会抛异常.is操作符通常这样使用: if(o is Employee) { Employee e=(Employee) ...