在Python中将返回变量重新指定给函数
我试图弄清楚为什么会出现“SyntaxError:invalid syntax”(语法错误:无效语法)变量标题突出显示为红色在Python中将返回变量重新指定给函数,python,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)
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")
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")
应该是这样的,如果出现进一步的错误,一定要说。我认为您需要正确缩进
try
和之后的内容,除了@MattCremeens:错误消息会指向其他地方。但是,如果没有完整的错误消息,我们无法真正帮助您,只能推测可能的错误。您还混合了制表符和空格(制表符大小为8个空格时,您将有正确的缩进,而Stack Overflow将在4个空格处显示制表符)。不要这样做;仅将空格用于缩进(编辑器可以将选项卡转换为空格)。因为您使用的是Python3,所以这很可能是您在这里出错的原因;Python3明确禁止混合缩进样式。OP是混合制表符和空格。制表符设置为8个空格(这是Python使用的),缩进是完全正确的。我按照您的建议修复了缩进,它工作了。非常感谢你!很乐意帮忙。如果是,请接受。干杯