」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 為什麼 BeautifulSoup 函數(如“find”和“select_one”)返回“None”?

為什麼 BeautifulSoup 函數(如“find”和“select_one”)返回“None”?

發佈於2024-11-22
瀏覽:699

Why do BeautifulSoup functions like `find` and `select_one` return `None`?

為什麼BeautifulSoup函數有時會傳回None

在BeautifulSoup中,搜尋單一結果的函數,例如find和select_one,如果在中沒有找到符合的元素,則返回None HTML。如果後續程式碼嘗試像實際元素一樣使用這些 None 值,則會導致 AttributeError 異常。

None 傳回的範例

考慮以下程式碼片段:

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
  • soup.sister: 傳回 None,因為 HTML 中沒有 標籤。
  • soup.find('a', class_='brother'): 傳回None 因為沒有class 屬性為的 標籤"brother."
  • soup.select_one('a.brother'): 回傳None ,原因與soup.find(...).
  • soup.select_one('a.brother').text: 引發AttributeError 因為None 沒有文字attribute.

]如何避免AttributeError: 'NoneType' object has no attribute...

為了避免 AttributeError 異常,必須優雅地處理 None 回傳。以下是一些最佳實踐:

  • 在嘗試存取屬性之前,使用條件語句檢查結果是否為 None。
  • 將結果指派給變數並使用 .has_attr() 檢查特定屬性是否存在。
  • 利用 try 和 except 區塊捕捉 AttributeError 異常。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3