Beautiful Soup - 移植舊程式碼



你可以透過以下更改匯入語句,使早期版本的 Beautiful Soup 程式碼與最新版本相容:

示例

from BeautifulSoup import BeautifulSoup
#becomes this:

from bs4 import BeautifulSoup

如果你收到 ImportError "No module named BeautifulSoup" 錯誤,這意味著你嘗試執行 Beautiful Soup 3 程式碼,但只安裝了 Beautiful Soup 4。類似地,如果你收到 ImportError "No module named bs4" 錯誤,是因為你嘗試執行 Beautiful Soup 4 程式碼,但只安裝了 Beautiful Soup 3。

Beautiful Soup 3 使用 Python 的 SGMLParser,這是一個在 Python 3.0 中已被移除的模組。Beautiful Soup 4 預設使用 html.parser,但你也可以使用 lxml 或 html5lib。

儘管 BS4 大部分與 BS3 向後相容,但其大多數方法已被棄用,併為符合 PEP 8 而改用了新名稱。

以下是一些示例:

replaceWith -> replace_with
findAll -> find_all
findNext -> find_next
findParent -> find_parent
findParents -> find_parents
findPrevious -> find_previous
getText -> get_text
nextSibling -> next_sibling
previousSibling -> previous_sibling
廣告
© . All rights reserved.