用Python爬取某吧的美图

Talk is cheap, show the code!

import re  
import urllib.request  
def getHtml(url):  
    page=urllib.request.urlopen(url)  
    html=page.read().decode('utf-8')  
    return html  
def getImag(html):  
    reg=r'src="(.*?\.jpg)" size'  
    imgre=re.compile(reg)  
    imglist=re.findall(imgre,html)  
    x=0  
    for imgurl in imglist:  
        urllib.request.urlretrieve(imgurl,'%s.jpg' %x)  
        x+=1  
html=getHtml('http://tieba.baidu.com/p/4894718605')  
print(getImag(html)) 

注:1.我用的Python版本为3.4

        2.在Python3.x版本中,需要导入的是urllib.request,这里不同于以前版本

        3.在爬的过程中遇到了:“TypeError:can't use a string pattern on a bytes-like object ”,这个问题,解决办法为将读取到的文件解码成”utf-8“,即将”html=page.read()“改为”html=page.read().decode('utf-8')“


猜你喜欢

转载自blog.csdn.net/u010592112/article/details/72854569