在BeautifulSoup中,搜索单个结果的函数,例如find和select_one,如果在中没有找到匹配的元素,则返回None HTML。如果后续代码尝试像实际元素一样使用这些 None 值,则会导致 AttributeError 异常。
考虑以下代码片段:
html_doc = "..." soup = BeautifulSoup(html_doc, 'html.parser') print(soup.sister) print(soup.find('a', class_='brother')) print(soup.select_one('a.brother')) soup.select_one('a.brother').text
为了避免 AttributeError 异常,必须优雅地处理 None 返回。以下是一些最佳实践:
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3