【问题标题】:How to solve this namespace conflict with BeautifulSoup?如何解决与 BeautifulSoup 的命名空间冲突?
【发布时间】:2016-02-20 04:52:08
【问题描述】:

我在使用 Python 命名空间时遇到了一些问题。

import bs4

>>> import bs4
>>> print type(x)
>>> <class 'bs4.element.NavigableString'>
>>> isinstance(x,bs4.element.NavigableString)
>>> True

但我想使用from bs4 import BeautifulSoup,然后出现错误

>>> from bs4 import BeautifulSoup
>>> print type(x)
>>> <class 'bs4.element.NavigableString'>
>>> isinstance(x,bs4.element.NavigableString)
>>> ...
NameError: name 'bs4' is not defined


isinstance(x,bs4.element.NavigableString)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
             What should go here? 

也检查了isinstance not working correctly with beautifulsoup(NameError),但对我没有帮助。

【问题讨论】:

  • 您需要import bs4 以及,或者将element 添加到您要导入的内容中 (from bs4 import BeautifulSoup, element) 然后直接访问它 (isinstance(x, element.NavigableString) .
  • 谢谢!您想将此作为答案发布吗
  • 作为记录(据我所知),只要您正确引用名称,使用 import modulefrom module import function 并没有错。

标签: python python-2.7 beautifulsoup


【解决方案1】:

正如@jonrsharpe 所说,将导入语句替换为from bs4 import BeautifulSoup, element,将有问题的行替换为element.NavigableString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多