捕获BeautifulGroup HTMLParseError异常

2024-09-28 22:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我从BeutifulsoupHTMLParseError: expected name token at u'<![0Y', at line 1371, column 24-中得到异常,这是因为我正在读取的html格式错误。在

如何捕获此错误-我已尝试过

 try: 
     ... 
 except HTMLParseError:
     pass

但这会导致错误NameError: global name 'HTMLParseError' is not defined

我也尝试过except BeautifulSoup.HTMLParseError:,但这会导致错误AttributeError: type object 'BeautifulSoup' has no attribute 'HTMLParseError'

更广泛地说,当我从正在使用的包中收到一个自定义错误时,如何才能“计算出”需要什么样的异常来处理它?在


Tags: nametokenhtml格式错误linecolumnpass
2条回答

你试过捕捉NameError异常吗?在

如果你抓不到,试试这个:

try:
    # error happens
except Exception as e:
    # log the exception here
    print(e)

BeautifulGroup正在从HTMLParser库引发HtmlParserError。尝试从该库导入错误,然后再在Try中使用它/除了:

from HTMLParser import HTMLParseError

try:
    # error happens
except HTMLParseError:
    pass

有关HTMLParse库的更多信息是here。在

请参阅BeautifulSoup源代码here中错误发生的位置。在

相关问题 更多 >