跟着哔哩哔哩视频开始写爬虫啦,目标:下载白死不得姐的视频
1.2.7->3重要改变:
1.import urllib2替换为
import urllib.request
2.html=urllib.request.urlopen(xxx).read()
后要 html=html.decode('UTF-8')
防止出现:TypeError: cannot use a string pattern on a bytes-like object
2.正则表达式
reg=r'data-mp4="(.*?)"'
reg就是正则表达式 r’xxx’:r的目的啊是以原生字符串显示(即:/n不换行而直接显示/n这个字符串) xxx即中间的匹配式子
.?是王能替换变量,在这里表示MP4的网址 ()扩住.?表示把这个替换的变量取出,如果没有括号意思就是只匹配不取出
3.完整代码:
import urllib.request
import urllib.error
import re
print("plz input 1~50")
page=input("which budejie page you want to download?(1~50)")
page=int(page)
while page>50:
print("plz input 1~50")
page=input("which budejie page you want to download?(1~50)")
page=int(page)
headers={'User-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
url="http://www.budejie.com/"+str(page)
request=urllib.request.Request(url,headers=headers)
html=urllib.request.urlopen(request).read()
html=html.decode('UTF-8')#2.7->3!!!!!!!!
reg=r'="(.*?).mp4'
mp4list=re.findall(reg,html)
for i in mp4list:
print("downloading:"+i+".mp4")
filename=re.split('/',i)[-1]+".mp4"
urllib.request.urlretrieve(i+".mp4",filename)
这里正则表达式一开始写的智能爬取一半视频,经过修改,直接找地址.mp4的方式写正则,最后用地址的时候再给加上”.mp4”就可以完美爬取