Python 如果没有 AttributeError

Bij*_*jan 2 python attributeerror

我有一个返回网页标题的小脚本

title = BeautifulSoup(urllib2.urlopen(URL)).title.string
Run Code Online (Sandbox Code Playgroud)

但并非所有网站都指定<title>标签,在这种情况下我的脚本会返回

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

title如果网页上有标题,有没有办法让变量等于标题?

我经受过考验

if BeautifulSoup(urllib2.urlopen(url)).title.string.strip():
    print BeautifulSoup(urllib2.urlopen(url)).title.string.strip()
else:
    print url
Run Code Online (Sandbox Code Playgroud)

但它仍然会引发 AttributeError 错误

小智 5

try:
    title = BeautifulSoup(urllib2.urlopen(URL)).title.string
except AttributeError:
    title = url
Run Code Online (Sandbox Code Playgroud)