【发布时间】:2015-04-07 20:40:35
【问题描述】:
我正在用
解析 HTML 文本Telephone = soup.find(itemprop="telephone").get_text()
如果电话号码在 HTML 中 itemprop 标记之后,我会收到一个号码并得到输出(例如,"Telephone Number: 34834243244")。
当然,如果没有找到电话号码,我会收到AttributeError: 'NoneType' object has no attribute 'get_text'。没关系。
但是,在这种情况下,我希望 Python 不打印错误消息,而是设置 Telephone = "-" 并获取输出 "Telephone Number: -"。
谁能建议如何处理这个错误?
【问题讨论】:
-
两个选择,要么:预先测试
is None;或try并抓住AttributeError。
标签: python attributeerror