心血来潮写了个多线程抓妹子图,虽然代码还是有一些瑕疵,但是还是记录下来,分享给大家。
Pic_downloader.py
# -*- coding: utf-8 -*- """ Created on Fri Aug 07 17:30:58 2015 @author: Dreace """ import urllib2 import sys import time import os import random from multiprocessing.dummy import Pool as ThreadPool type_ = sys.getfilesystemencoding() def rename(): return time.strftime("%Y%m%d%H%M%S") def rename_2(name): if len(name) == 2: name = '0' + name + '.jpg' elif len(name) == 1: name = '00' + name + '.jpg' else: name = name + '.jpg' return name def download_pic(i): global count global time_out if Filter(i): try: content = urllib2.urlopen(i,timeout = time_out) url_content = content.read() f = open(repr(random.randint(10000,999999999)) + "_" + rename_2(repr(count)),"wb") f.write(url_content) f.close() count += 1 except Exception, e: print i + "下载超时,跳过!".decode("utf-8").encode(type_) def Filter(content): for line in Filter_list: line=line.strip('\n') if content.find(line) == -1: return True def get_pic(url_address): global pic_list try: str_ = urllib2.urlopen(url_address, timeout = time_out).read() url_content = str_.split("\"") for i in url_content: if i.find(".jpg") != -1: pic_list.append(i) except Exception, e: print "获取图片超时,跳过!".decode("utf-8").encode(type_) MAX = 2 count = 0 time_out = 60 thread_num = 30 pic_list = [] page_list = [] Filter_list = ["imgsize.ph.126.net","img.ph.126.net","img2.ph.126.net"] dir_name = "C:\Photos\\"+rename() os.makedirs(dir_name) os.chdir(dir_name) start_time = time.time() url_address = "http://sexy.faceks.com/?page=" for i in range(1,MAX + 1): page_list.append(url_address + repr(i)) page_pool = ThreadPool(thread_num) page_pool.map(get_pic,page_list) print "获取到".decode("utf-8").encode(type_),len(pic_list),"张图片,开始下载!".decode("utf-8").encode(type_) pool = ThreadPool(thread_num) pool.map(download_pic,pic_list) pool.close() pool.join() print count,"张图片保存在".decode("utf-8").encode(type_) + dir_name print "共耗时".decode("utf-8").encode(type_),time.time() - start_time,"s"
我们来看下一个网友的作品
#coding: utf-8 ############################################################# # File Name: main.py # Author: mylonly # mail: mylonly@gmail.com # Created Time: Wed 11 Jun 2014 08:22:12 PM CST ######################################################################### #!/usr/bin/python import re,urllib2,HTMLParser,threading,Queue,time #各图集入口链接 htmlDoorList = [] #包含图片的Hmtl链接 htmlUrlList = [] #图片Url链接Queue imageUrlList = Queue.Queue(0) #捕获图片数量 imageGetCount = 0 #已下载图片数量 imageDownloadCount = 0 #每个图集的起始地址,用于判断终止 nextHtmlUrl = '' #本地保存路径 localSavePath = '/data/1920x1080/' #如果你想下你需要的分辨率的,请修改replace_str,有如下分辨率可供选择1920x1200,1980x1920,1680x1050,1600x900,1440x900,1366x768,1280x1024,1024x768,1280x800 replace_str = '1920x1080' replaced_str = '960x600' #内页分析处理类 class ImageHtmlParser(HTMLParser.HTMLParser): def __init__(self): self.nextUrl = '' HTMLParser.HTMLParser.__init__(self) def handle_starttag(self,tag,attrs): global imageUrlList if(tag == 'img' and len(attrs) > 2 ): if(attrs[0] == ('id','bigImg')): url = attrs[1][1] url = url.replace(replaced_str,replace_str) imageUrlList.put(url) global imageGetCount imageGetCount = imageGetCount + 1 print url elif(tag == 'a' and len(attrs) == 4): if(attrs[0] == ('id','pageNext') and attrs[1] == ('class','next')): global nextHtmlUrl nextHtmlUrl = attrs[2][1]; #首页分析类 class IndexHtmlParser(HTMLParser.HTMLParser): def __init__(self): self.urlList = [] self.index = 0 self.nextUrl = '' self.tagList = ['li','a'] self.classList = ['photo-list-padding','pic'] HTMLParser.HTMLParser.__init__(self) def handle_starttag(self,tag,attrs): if(tag == self.tagList[self.index]): for attr in attrs: if (attr[1] == self.classList[self.index]): if(self.index == 0): #第一层找到了 self.index = 1 else: #第二层找到了 self.index = 0 print attrs[1][1] self.urlList.append(attrs[1][1]) break elif(tag == 'a'): for attr in attrs: if (attr[0] == 'id' and attr[1] == 'pageNext'): self.nextUrl = attrs[1][1] print 'nextUrl:',self.nextUrl break #首页Hmtl解析器 indexParser = IndexHtmlParser() #内页Html解析器 imageParser = ImageHtmlParser() #根据首页得到所有入口链接 print '开始扫描首页...' host = 'http://desk.zol.com.cn' indexUrl = '/meinv/' while (indexUrl != ''): print '正在抓取网页:',host+indexUrl request = urllib2.Request(host+indexUrl) try: m = urllib2.urlopen(request) con = m.read() indexParser.feed(con) if (indexUrl == indexParser.nextUrl): break else: indexUrl = indexParser.nextUrl except urllib2.URLError,e: print e.reason print '首页扫描完成,所有图集链接已获得:' htmlDoorList = indexParser.urlList #根据入口链接得到所有图片的url class getImageUrl(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for door in htmlDoorList: print '开始获取图片地址,入口地址为:',door global nextHtmlUrl nextHtmlUrl = '' while(door != ''): print '开始从网页%s获取图片...'% (host+door) if(nextHtmlUrl != ''): request = urllib2.Request(host+nextHtmlUrl) else: request = urllib2.Request(host+door) try: m = urllib2.urlopen(request) con = m.read() imageParser.feed(con) print '下一个页面地址为:',nextHtmlUrl if(door == nextHtmlUrl): break except urllib2.URLError,e: print e.reason print '所有图片地址均已获得:',imageUrlList class getImage(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global imageUrlList print '开始下载图片...' while(True): print '目前捕获图片数量:',imageGetCount print '已下载图片数量:',imageDownloadCount image = imageUrlList.get() print '下载文件路径:',image try: cont = urllib2.urlopen(image).read() patter = '[0-9]*\.jpg'; match = re.search(patter,image); if match: print '正在下载文件:',match.group() filename = localSavePath+match.group() f = open(filename,'wb') f.write(cont) f.close() global imageDownloadCount imageDownloadCount = imageDownloadCount + 1 else: print 'no match' if(imageUrlList.empty()): break except urllib2.URLError,e: print e.reason print '文件全部下载完成...' get = getImageUrl() get.start() print '获取图片链接线程启动:' time.sleep(2) download = getImage() download.start() print '下载图片链接线程启动:'
批量抓取指定网页上的所有图片
# -*- coding:utf-8 -*- # coding=UTF-8 import os,urllib,urllib2,re url = u"http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=python&oq=python&rsp=-1" outpath = "t:\\" def getHtml(url): webfile = urllib.urlopen(url) outhtml = webfile.read() print outhtml return outhtml def getImageList(html): restr=ur'(' restr+=ur'http:\/\/[^\s,"]*\.jpg' restr+=ur'|http:\/\/[^\s,"]*\.jpeg' restr+=ur'|http:\/\/[^\s,"]*\.png' restr+=ur'|http:\/\/[^\s,"]*\.gif' restr+=ur'|http:\/\/[^\s,"]*\.bmp' restr+=ur'|https:\/\/[^\s,"]*\.jpeg' restr+=ur'|https:\/\/[^\s,"]*\.jpeg' restr+=ur'|https:\/\/[^\s,"]*\.png' restr+=ur'|https:\/\/[^\s,"]*\.gif' restr+=ur'|https:\/\/[^\s,"]*\.bmp' restr+=ur')' htmlurl = re.compile(restr) imgList = re.findall(htmlurl,html) print imgList return imgList def download(imgList, page): x = 1 for imgurl in imgList: filepathname=str(outpath+'pic_%09d_%010d'%(page,x)+str(os.path.splitext(urllib2.unquote(imgurl).decode('utf8').split('/')[-1])[1])).lower() print '[Debug] Download file :'+ imgurl+' >> '+filepathname urllib.urlretrieve(imgurl,filepathname) x+=1 def downImageNum(pagenum): page = 1 pageNumber = pagenum while(page <= pageNumber): html = getHtml(url)#获得url指向的html内容 imageList = getImageList(html)#获得所有图片的地址,返回列表 download(imageList,page)#下载所有的图片 page = page+1 if __name__ == '__main__': downImageNum(1)
以上就是给大家汇总的3款Python实现的批量抓取妹纸图片的代码了,希望对大家学习Python爬虫能够有所帮助。

Python의 유연성은 다중 파리가 지원 및 동적 유형 시스템에 반영되며, 사용 편의성은 간단한 구문 및 풍부한 표준 라이브러리에서 나옵니다. 유연성 : 객체 지향, 기능 및 절차 프로그래밍을 지원하며 동적 유형 시스템은 개발 효율성을 향상시킵니다. 2. 사용 편의성 : 문법은 자연 언어에 가깝고 표준 라이브러리는 광범위한 기능을 다루며 개발 프로세스를 단순화합니다.

Python은 초보자부터 고급 개발자에 이르기까지 모든 요구에 적합한 단순성과 힘에 호의적입니다. 다목적 성은 다음과 같이 반영됩니다. 1) 배우고 사용하기 쉽고 간단한 구문; 2) Numpy, Pandas 등과 같은 풍부한 라이브러리 및 프레임 워크; 3) 다양한 운영 체제에서 실행할 수있는 크로스 플랫폼 지원; 4) 작업 효율성을 향상시키기위한 스크립팅 및 자동화 작업에 적합합니다.

예, 하루에 2 시간 후에 파이썬을 배우십시오. 1. 합리적인 학습 계획 개발, 2. 올바른 학습 자원을 선택하십시오. 3. 실습을 통해 학습 된 지식을 통합하십시오. 이 단계는 짧은 시간 안에 Python을 마스터하는 데 도움이 될 수 있습니다.

Python은 빠른 개발 및 데이터 처리에 적합한 반면 C는 고성능 및 기본 제어에 적합합니다. 1) Python은 간결한 구문과 함께 사용하기 쉽고 데이터 과학 및 웹 개발에 적합합니다. 2) C는 고성능과 정확한 제어를 가지고 있으며 게임 및 시스템 프로그래밍에 종종 사용됩니다.

Python을 배우는 데 필요한 시간은 개인마다 다릅니다. 주로 이전 프로그래밍 경험, 학습 동기 부여, 학습 리소스 및 방법 및 학습 리듬의 영향을받습니다. 실질적인 학습 목표를 설정하고 실용적인 프로젝트를 통해 최선을 다하십시오.

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

드림위버 CS6
시각적 웹 개발 도구
