将返回变量重新分配给Python中的函数

时间:2016-09-09 16:57:56

标签: python

我想弄清楚为什么我得到一个“SyntaxError:invalid syntax”变量标题突出显示为红色

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
    html=urlopen(url)
    except HTTPError as e:
    return None
    try:
    bsObj=BeautifulSoup(html.read())
    title=bsObj.body.h1
    except AttributeError as e:
    return None
    return title
title=getTitle("http://....html")

1 个答案:

答案 0 :(得分:0)

Python对空格,缩进非常敏感,以保持代码看起来干净。从我所看到的,你需要尝试你的try / except语句:

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
        html=urlopen(url)
    except HTTPError as e:
        return None
    try:
        bsObj=BeautifulSoup(html.read())
        title=bsObj.body.h1
    except AttributeError as e:
        return None
    return title
title=getTitle("http://....html")

应该是这样,如果发生进一步的错误,请说。