使用爬虫下载图片

import urllib#调用urllib模块
import re#调用正则模块

def  getHtml(url):
    if url is None:#如果url为空的话直接return
        return
    html=urllib.urlopen(url)#使用urllib.urlopen打开网页
    if html.getcode()!=200:
        return
    page=html.read()#返回网页信息
    return page

def getImg(page):
    if page is None:
        return
    reg=r'src="(.+?\.jpg)" pic_ext'#匹配规则
    imgre=re.compile(reg)#生成一个正则对象(正则的工厂方法)
    imgres=re.findall(imgre,page)#进行匹配
    x=0
    for imgurl in imgres:
        urllib.urlretrieve(imgurl,'%s.jpg'% x)#将文件下载到本地
        x+=1
'''
使用爬虫下载图片小程序
'''

h=getHtml('http://tieba.baidu.com/p/2460150866')
print getImg(h)

 

posted @ 2017-01-11 07:23  200六  阅读(333)  评论(0编辑  收藏  举报