#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import urllib,urllib2;
#通過url獲取網頁
def getHtml(url):
# 要設置請求頭,讓服務器知道不是機器人
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
request=urllib2.Request(url,headers=headers);
page = urllib2.urlopen(request);
html = page.read()
return html
#通過正則表達式來獲取圖片地址,並下載到本地
def getImg(html):
reg = r'src="(.+?\.jpg)"'
imgre = re.compile(reg)
imglist = imgre.findall(html)
x = 0
for imgurl in imglist:
print imgurl;
#通過urlretrieve函數把數據下載到本地的D:\\images,所以你需要創建目錄
urllib.urlretrieve(imgurl, 'D:\\images\\%s.jpg' % x)
x = x + 1
html = getHtml("http://www.qiushibaike.com/imgrank/")
getImg(html)