NoneType'对象没有'group'属性

28 投票
4 回答
172429 浏览
提问于 2025-04-17 17:07

有人能帮我看看这段代码吗?我想写一个Python脚本来播放视频,我找到一个可以下载YouTube视频的文件。但我不是很明白发生了什么,而且我也搞不清楚这个错误。

错误信息:

AttributeError: 'NoneType' object has no attribute 'group'

错误追踪信息:

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;')

代码片段:

(第66到71行)

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

if videoUrl is not None:
    print('Video URL cannot be found')
    exit(1)

(第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

4 个回答

3

我想提一下在这个情况下新出现的walrus 运算符,因为这个问题经常被标记为重复,而这个运算符可能很简单地解决这个问题。


Python 3.8之前,我们需要这样写:

match = re.search(pattern, string, flags)
if match:
    # do sth. useful here

Python 3.8开始,我们可以这样写:

if (match := re.search(pattern, string, flags)) is not None:
    # do sth. with match

其他语言早就有这个功能了(比如CPHP),但我觉得这样写代码会更简洁。


对于上面的代码,这可以是:

def getVideoUrl(content):
    if (fmtre := re.search('(?<=fmt_url_map=).*', content)) is None:
        return None
    ...
6

你用 regex 来匹配网址,但匹配不上,所以结果是 None

None 这种类型是没有 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
33

错误出在你的第11行,你的 re.search 没有找到任何结果,也就是返回了 None,然后你又试图调用 fmtre.group,但此时 fmtreNone,所以就出现了 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

撰写回答