python抓取网页图片并放到指定文件夹

yipeiwu_com5年前Python爬虫

python抓取网站图片并放到指定文件夹

复制代码 代码如下:

# -*- coding=utf-8 -*-
import urllib2
import urllib
import socket
import os
import re
def Docment():
    print u'把文件存在E:\Python\图(请输入数字或字母)'
    h=raw_input()
    path=u'E:\Python\图'+str(h)
    if not os.path.exists(path):
        os.makedirs(path)
    return path
def getallurl(html):
    reg=r"a href='(.*?\.htm)'"
    allurl= re.compile(reg)
    allList = re.findall(allurl,html)
    return allList
def getHTML(url):
    url=url
    req_header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
    req_timeout = 20
    html='cuowu'
    try:
        req = urllib2.Request(url,None,req_header)
        resp = urllib2.urlopen(req,None,req_timeout)
        html = resp.read()
    except urllib2.URLError as e:
        print e.message
    except socket.timeout as e:
        getHTML(url,fu)
    return html
def getImg(html,path):
    reg = r'img class=IMG_show border=0 src=(.*?\.jpg)'
    imgre= re.compile(reg)
    imgList = re.findall(imgre, html)
    if imgList:
        print 'ghasghg',path
        for imgurl in imgList:
            print imgurl
            content2=urllib2.urlopen(imgurl).read()
            with open(path+'/'+imgurl[-7:],'wb') as code:
                code.write(content2)
    else:
        return 0
def getallurl(html):
    reg=r"a href='(.*?\.htm)'"
    allurl= re.compile(reg)
    allList = re.findall(allurl,html)
    return allList
j=1
i=0
print u'请输入网址:'
ul=raw_input()
print u'开始下载'
print u'第'+str(j)+u'页'
html=getHTML(ul)
allList=getallurl(html)
path=Docment()
getImg(html,path)
while i<len(allList):
    for lis in allList:
        l=lis[i]
        url=r'http://www.umei.cc/p/gaoqing/rihan/'+lis
        i=i+1
        j=j+1
        html=getHTML(url)
        getImg(html,path)
        print u'第'+str(j)+u'页'
    else:
        print u'下载完毕'

相关文章

python抓取百度首页的方法

本文实例讲述了python抓取百度首页的方法。分享给大家供大家参考。具体实现方法如下: import urllib def downURL(url,filename): try:...

python编写简单爬虫资料汇总

python编写简单爬虫资料汇总

  爬虫真是一件有意思的事儿啊,之前写过爬虫,用的是urllib2、BeautifulSoup实现简单爬虫,scrapy也有实现过。最近想更好的学习爬虫,那么就尽可能的做记录吧。这篇博客...

利用Python2下载单张图片与爬取网页图片实例代码

利用Python2下载单张图片与爬取网页图片实例代码

前言 一直想好好学习一下Python爬虫,之前断断续续的把Python基础学了一下,悲剧的是学的没有忘的快。只能再次拿出来滤了一遍,趁热打铁,通过实例来实践下,下面这篇文章主要介绍了关于...

Python 正则表达式爬虫使用案例解析

现在拥有了正则表达式这把神兵利器,我们就可以进行对爬取到的全部网页源代码进行筛选了。 下面我们一起尝试一下爬取内涵段子网站: http://www.neihan8.com/articl...

Python实现的爬虫功能代码

本文实例讲述了Python实现的爬虫功能。分享给大家供大家参考,具体如下: 主要用到urllib2、BeautifulSoup模块 #encoding=utf-8 import re...