使用脚本语言编写一个爬虫程序,访问HTML页面(在找这个页面的地址时,着实费了一番功夫),找出所有JPG图片的地址,然后下载保存到本地即可。这里比较值得一提的是,微软比较地道,我爬虫出来的所有的图片地址均是有效的,如果出现无效的地址,程序估计该挂了。我曾试着使用不同的线程,但是所开的线程量挺大,虽然还没有达到进程所开线程的极限,但是却是问题百出。无奈只能委曲求全。还有值得一提的是,在微软HTML页面所获得的均是图片的完整地址,不需要再进行拼接,着实省去不少麻烦。在试着抓取“e周纪实摄影”上的图片地址时,图片的完整地址需要自己拼接。下面附上代码:
# encoding:utf-8
import re
import urllib
#定义得到HTML页面的函数
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getContents(url):
#得到目录的链接
contentHtml = getHtml(url)
#def rule to find imgurl定义正则
contentRule = r'href="(http://ieday.cn/article-.+?\.html)"'
global contentList
contentList = re.findall(contentRule, contentHtml)
print contentList
def getJpg(url):
html = getHtml(url)
rule = r'href="(.+?\.jpg)"'
imgUrlList = re.findall(rule, html)
if not imgUrlList:
print "<---%s is none-->" %url
for imgUrl in imgUrlList:
#使用url中的目录做名字,避免重复下载
_fileName = imgUrl.replace('/', '_')
fileName = "D:\Thinkpad_WallPaper\windows\%s"%(_fileName.replace(':', '_'))
fullImgUrl = imgUrl
print "downloading...",fullImgUrl
urllib.urlretrieve(fullImgUrl, fileName)
print "start..."
getJpg("http://windows.microsoft.com/zh-cn/windows/wallpaper?T1=all")
print "end..."