python2.7爬图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013716535/article/details/78955534

背景

老板要求自学python,第一件事就是使用pytho爬取网易首页的图片。因为有学过简明python2.7所以现在依旧用的2.7版本,然后直接百度怎么操作,所以代码可能跟网上有些重叠。

# -*- coding: utf-8 -*-  
import re  
import urllib
import urllib2  
import os     
def getHtml(url):  
        page = urllib2.urlopen(url)  
        html = page.read()
        print html
        return html  
def mkdir(path):  
        path = path.strip()  
        isExists = os.path.exists(path)  
        if not isExists:  
            print u'新建了名字叫做',path,u'的文件夹'   
            os.makedirs(path)
            print 6
            return True  
        else:   
            print u'名为',path,u'的文件夹已经创建成功'  
            return False    
def saveImages(imglist,name):  
        number = 1
        for imageURL in imglist:
            print 13
            splitPath = imageURL.split('.')  
            fTail = splitPath.pop()
            print 12
            if len(fTail) > 3:  
                fTail = 'jpg'  
            fileName = name + "/" + str(number) + "." + fTail
            print 8
            # 对于每张图片地址,进行保存  
            try:  
                u = urllib2.urlopen(imageURL)  
                data = u.read()  
                f = open(fileName,'wb+')  
                f.write(data)
                print u'正在保存的一张图片为',fileName  
                f.close()  
            except urllib2.URLError as e:  
                print (e.reason)  
            number += 1   
def getAllImg(html):  
        reg = r'src="(.+?\.jpg)" pic_ext'  
        imgre = re.compile(reg)
        print imgre
        imglist = imgre.findall(html)
        print 7
        print imglist
        return imglist   
if __name__ == '__main__':  
        html = getHtml("http://tieba.baidu.com/p/2460150866")  
        path = u'图片1'  
        mkdir(path)
        imglist = getAllImg(html)
        print 10
        saveImages(imglist,path) 

局限性很大,首先这个代码换了网易的地址,是并不会爬下图的,因为获取图片的方式是用的正则,然而每个网站图片的表达方式可能不一样,所以下一节将换取一个更具有通用性的代码。

猜你喜欢

转载自blog.csdn.net/u013716535/article/details/78955534
今日推荐