在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