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.