'NoneType'对象没有属性'group'

Dav*_*vid 17 python youtube download

有人可以帮我这个代码吗?我正在尝试制作一个可以播放视频的python脚本,我发现这个文件可以下载Youtube视频.我不完全确定发生了什么,我无法弄清楚这个错误.

错误:

AttributeError: 'NoneType' object has no attribute 'group'
Run Code Online (Sandbox Code Playgroud)

追溯:

Traceback (most recent call last):
  File "youtube.py", line 67, in <module>
    videoUrl = getVideoUrl(content)
  File "youtube.py", line 11, in getVideoUrl
    grps = fmtre.group(0).split('&amp;')
Run Code Online (Sandbox Code Playgroud)

代码段:

(第66-71行)

content = resp.read()
videoUrl = getVideoUrl(content)

if videoUrl is not None:
    print('Video URL cannot be found')
    exit(1)
Run Code Online (Sandbox Code Playgroud)

(第9-17行)

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None
Run Code Online (Sandbox Code Playgroud)

Ian*_*hon 21

该错误是在第11行,你re.search是不会回来的结果,即None,然后你想打电话fmtre.group,但fmtre就是None,因此AttributeError.

你可以尝试:

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    if fmtre is None:
        return None
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None
Run Code Online (Sandbox Code Playgroud)


Tan*_*Woo 6

你用来regex匹配url,但是匹配不到,所以结果是None

并且Nonetype 没有该group属性

您应该在detect结果中添加一些代码

如果不能匹配规则,则不应在代码下继续

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    if fmtre is None:
        return None         # if fmtre is None, it prove there is no match url, and return None to tell the calling function 
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None
Run Code Online (Sandbox Code Playgroud)