BeautifulSoup Python 3.4 中的无效语法(在 2to3.py 之后)

BeautifulSoup invalid syntax in Python 3.4 (after 2to3.py)

我正在尝试在 Python 3.4 中安装 Beautiful Soup 4。我从命令行安装它,(得到无效语法错误,因为我没有转换它),运行 2to3.py 转换脚本到 bs4 现在我得到一个新的无效语法错误.

>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
    from bs4 import BeautifulSoup
  File "C:\Python34\bs4\__init__.py", line 30, in <module>
    from .builder import builder_registry, ParserRejectedMarkup
  File "C:\Python34\bs4\builder\__init__.py", line 4, in <module>
    from bs4.element import (
  File "C:\Python34\bs4\element.py", line 1213
    print 'Running CSS selector "%s"' % selector
                                    ^
SyntaxError: Missing parentheses in call to 'print'

有什么想法吗?

BeautifulSoup 4 不需要 需要在 Python 上手动转换为 运行 3. 您正在尝试 运行 代码仅与 Python 2 兼容;看来您未能正确转换代码库。

来自BeautifulSoup 4 homepage

Beautiful Soup 4 works on both Python 2 (2.6+) and Python 3.

现在抛出异常的行应该读作:

print('Running CSS selector "%s"' % selector)

代码库确实使用 Python 2 语法,但 setup.py 安装程序会为您将其转换为兼容的 Python 3 语法。确保使用 pip:

安装项目
pip install beautifulsoup4

或使用与 Python 3.4 捆绑的 pip 版本:

python3.4 -m pip install beautifulsoup4

或使用easy_install:

easy_install beautifulsoup4

如果您只下载了压缩包,至少 运行

python3.4 setup.py install

让安装程序为您正确转换代码库;转换后的代码已 复制到您的 Python 设置中 。您可以在 运行 执行命令后丢弃下载的源目录,请参阅 How installation works

或者,运行:

python3.4 setup.py build

并复制到 build/lib 目录。同样,不要 使用原始源目录,因为它未被触及。