使用爬虫下载图片

Posted 200六

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用爬虫下载图片相关的知识,希望对你有一定的参考价值。

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=rsrc="(.+?\.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)

 

以上是关于使用爬虫下载图片的主要内容,如果未能解决你的问题,请参考以下文章