您的位置:首页 > 编程语言 > Python开发

python美女图片抓取

2015-11-24 08:54 411 查看
python新手,从网上自学自卖,下面是刚刚抓下来的图片





代码如下:

#-*-coding:utf-8-*-

import os
import re
import uuid
import urllib2
import cookielib

'''获取文件后缀名'''
def get_file_extension(file):
return os.path.splitext(file)[1]

'''創建文件目录,并返回该目录'''
def mkdir(path):
# 去除左右两边的空格
path=path.strip()
# 去除尾部 \符号
path=path.rstrip("\\")

if not os.path.exists(path):
os.makedirs(path)

return path

'''自动生成一个唯一的字符串,固定长度为36'''
def unique_str():
return str(uuid.uuid1())

'''
抓取网页文件内容,保存到内存

@url 欲抓取文件 ,path+filename
'''
def get_file(url):
try:
cj=cookielib.LWPCookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

req=urllib2.Request(url)
operate=opener.open(req)
data=operate.read()
return data
except BaseException, e:
print e
print url
return None

'''
保存文件到本地

@path 本地路径
@file_name 文件名
@data 文件内容
'''
def save_file(path, file_name, data):
if data == None:
return

mkdir(path)
if(not path.endswith("/")):
path=path+"/"
file=open(path+file_name, "wb")
file.write(data)
file.flush()
file.close()

def getImg(html,path,file_name):
# reg = r'src="(.+?\.jpg)" pic_ext'
reg2 = r'http://.*.jpg'
imgre = re.compile(reg2)
imglist = imgre.findall(html)
x = 0
for imgurl in imglist:
save_file(path + file_name, str(x) +".jpg", get_file(imgurl))
x = x + 1

def scrap_pictures():
path = "E:\图片-tmp\\"
for x in range(16):
url = "http://www.niuuu.com/meitu/" + str(45886 + x) + "/"
getImg(get_file(url), path, str(x))
#获取文件后缀名
# print get_file_extension("123.jpg");

#創建文件目录,并返回该目录
#print mkdir("d:/ljq")

#自动生成一个唯一的字符串,固定长度为36
# print unique_str()

# url="http://www.niuuu.com/meitu/45901/";
# html = get_file(url)
# category = ''
# save_file("C:\Users\Administrator\Desktop\spider\data", "123.html", html)
# getImg(html)

scrap_pictures()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 图片 os