一、参考文章

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-爬取妹子图(单线程和多线程版本)的更多相关文章

  1. python爬取妹子图全站全部图片-可自行添加-线程-进程爬取,图片去重

    from bs4 import BeautifulSoupimport sys,os,requests,pymongo,timefrom lxml import etreedef get_fenlei ...

  2. Python 爬取 妹子图(技术是无罪的)

    ... #!/usr/bin/env python import urllib.request from bs4 import BeautifulSoup def crawl(url): header ...

  3. Python 爬取妹子图(技术是无罪的)

    ... import requests from bs4 import BeautifulSoup import os import sys class mzitu(): def html(self, ...

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

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

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

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

  6. python 爬取妹子

    爬取妹子图片 网址:https://www.mzitu.com/jiepai/ 2019-06-13 环境WIN10 1903 python 3.7.3 个人习惯先在IDLE中进行调试 import ...

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

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

  8. python爬取斗图网中的 “最新套图”和“最新表情”

    1.分析斗图网 斗图网地址:http://www.doutula.com 网站的顶部有这两个部分: 先分析“最新套图” 发现地址栏变成了这个链接,我们在点击第二页 可见,每一页的地址栏只有后面的pag ...

  9. Python爬取 斗图表情,让你成为斗图大佬

    话不多说,上结果(只爬了10页内容) 上代码:(可直接运行)   用到Xpath #encoding:utf-8 # __author__ = 'donghao' # __time__ = 2018/ ...

随机推荐

  1. 使用Rapidxml读取xml文件

    现有xml文件如上,写在一个string中.需要获取节点上元素的类别和属性信息,并存储到结构体表中. 结构体如下: 得到的结果如下:

  2. 在基于debian的deepin或者Ubuntu上双等号“==”和双中括号“[[]]”不能使用的真相

    使用的deepin-linux,今天写shell脚本的时候,忽然发现 sh test.sh 会报错[[: not found ,双等号和双中括号都不能使用了,很郁闷,后来探索发现,sh其实是dash的 ...

  3. add two nums

    问题描述: 给定两个链表,计算出链表对应位置相加的和,如果和大于10要往后进位.用链表返回结果.其实上是一种大数加法.可以把一个大数倒着写存入链表,然后两个链表相加就是所需要的大数相加的和 输入 2 ...

  4. 用ECMAScript4 ( ActionScript3) 实现Unity的热更新 -- 使用FairyGUI (一)

    我们的热更新脚本在实际使用中,当然也要支持常用的第三方组件,例如这里介绍一个非常实用的第三方UI库:FairyGUI. 什么是FairyGUI 这里照搬FaiyGUI官网的介绍: 重新定义 UI 制作 ...

  5. cxf webservice生成客户端代码及调用服务端遇到的问题

    1.  从网上下载cxf开发的工具 apache-cxf-3.1.4.zip, 解压文件,找到apache-cxf-3.1.4\bin目录,里面包含一个wsdl2java文件 2. 设置环境变量 1. ...

  6. webpack学习之路01

    webpack是什么 1.模块化 能将css等静态文件模块化 2.借助于插件和加载器 webpack优势是什么 1.代码分离 各做各的 2.装载器(css,sass,jsx,es6等等) 3.智能解析 ...

  7. Reactor三种线程模型与Netty线程模型

    文中所讲基本都是以非阻塞IO.异步IO为基础.对于阻塞式IO,下面的编程模型几乎都不适用 Reactor三种线程模型 单线程模型 单个线程以非阻塞IO或事件IO处理所有IO事件,包括连接.读.写.异常 ...

  8. ES2015也就是ES6知识点持续更新

    ES6,全名:ECMAScript2015,先扯点其他的,ECMA是一个国际标准化组织,它最重要最重要的作用就是让ECMAScript这门语言标准化,什么意思呢?我们知道,js这门脚本语言是运行在浏览 ...

  9. 读取本地outlook邮件内容

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  10. Python_字符串之删除空白字符或某字符或字符串

    ''' strip().rstrip().lstrip()分别用来删除两端.右端.左端.连续的空白字符或字符集 ''' s='abc ' s2=s.strip() #删除空白字符 print(s2) ...