Python爬取百思不得姐的视频

 本次使用Python爬取百思不得姐中的视频,虽然其中视频提供了下载,但作为程序猿,你懂的(本次使用的Python的版本为3.6.1)。

       其源码如下:

#_*_ coding:utf-8 _*_  
import re  
import urllib.request  
user_agent='Mozilla/4.0(compatible;MSIE 5.5;Windows NT)'  
headers={'User-Agent':user_agent}  
def getHtml(url):  
    request=urllib.request.Request(url=url,headers=headers)  
    page=urllib.request.urlopen(request)  
    html=page.read().decode('utf-8')  
    #html=page.read()  
    return html  
def getVideo(html):  
    reg=r'data-mp4="(.*?\.mp4)"'  
    imgre=re.compile(reg)  
    imglist=re.findall(imgre,html)  
    x=0  
    for imgurl in imglist:  
        urllib.request.urlretrieve(imgurl,'%s.mp4' %x)  
        x+=1  
html=getHtml('http://www.budejie.com/video/')  
print(getVideo(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/72854534