1. 程式人生 > >python 下載 儲存 圖片的urllib.urlretrieve()函式 簡單用法

python 下載 儲存 圖片的urllib.urlretrieve()函式 簡單用法

執行環境python2.7

#coding=utf-8
import urllib
import re

def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html

def getImg(html):
    reg = r'src="(.+?\.jpg)" pic_ext'
    imgre = re.compile(reg)
    # 匹配出所有的圖片連結,返回結果為url列表
    imglist = re.findall(imgre,html)
    x = 0
    for imgurl in imglist:
        print(imgurl)
        # 將每張圖片儲存到本地
        urllib.urlretrieve(imgurl,'%s.jpg' % x)
        x+=1


html = getHtml("http://tieba.baidu.com/p/2460150866")

print getImg(html)