python正则获取不到值报错解决方案:AttributeError: 'NoneType' object has no attribute 'group'
以前的代码:
url_www = re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I).group(2)
若正则匹配不到值的时候则会报:AttributeError: 'NoneType' object has no attribute 'group'
正确的写法:
python版本>=3.8之后:
if (url_www := re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I)) is not None: url_www = url_www.group(2)
python版本 < 3.8:
url_www = re.search('https://(\w+).wanchemi.com/(\d+).html', w_url, flags=re.I) if url_www : url_www = url_www.group(2)
3.8 之后更精简
参考:https://stackoverflow.com/questions/15080078/nonetype-object-has-no-attribute-group