爬虫:爬取图片并保存在某路径下

import re
import urllib.request

def getHtml(url):
    page=urllib.request.urlopen(url)
    html=page.read()
    return html
    
def getImg(html):
    reg = r'src="([.*\S]*\.jpg)"'
    imgre=re.compile(reg)
    imglist=re.findall(imgre,html)
    return imglist

    
html=getHtml("http://www.win4000.com/zt/gaoqing.html")
html=html.decode("utf-8")
#print (1,html[:500])

imgList=getImg(html)
#print (2,imgList[:500])
imgName=0
for imgPath in imgList:
    try:
        pic_content = (urllib.request.urlopen(imgPath)).read()
        if len(pic_content)>4000:
            f = open('E:\\workspace-python\\testtest\\'+ str(imgName)+".jpg",'wb')
            f.write(pic_content)
            print(imgPath)
            f.close()
    except Exception as e:
        print(imgPath+" error")
    imgName += 1
print ("All Done")

 

posted @ 2019-01-11 22:45  糖葫芦有点甜  阅读(783)  评论(0编辑  收藏  举报