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 多线程的工作原理,及通过抓取400张图片这种IO密集型应用来查看多线程效率对比 import requests import urlparse imp...

python抓取百度首页的方法

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

python爬虫神器Pyppeteer入门及使用

python爬虫神器Pyppeteer入门及使用

前言 提起selenium想必大家都不陌生,作为一款知名的Web自动化测试框架,selenium支持多款主流浏览器,提供了功能丰富的API接口,经常被我们用作爬虫工具来使用。但是sele...

Scrapy爬虫实例讲解_校花网

学习爬虫有一段时间了,今天使用Scrapy框架将校花网的图片爬取到本地。Scrapy爬虫框架相对于使用requests库进行网页的爬取,拥有更高的性能。 Scrapy官方定义:Scrap...

Python之多线程爬虫抓取网页图片的示例代码

Python之多线程爬虫抓取网页图片的示例代码

目标 嗯,我们知道搜索或浏览网站时会有很多精美、漂亮的图片。 我们下载的时候,得鼠标一个个下载,而且还翻页。 那么,有没有一种方法,可以使用非人工方式自动识别并下载图片。美美哒。 那么请...