python - 在 BeautifulSoup 中插入新构造的元素

标签 python beautifulsoup

我试图在 <div id="apb"> 之前插入评论.该错误提出了一种解决方法,它确实有效。是我对 BeautifulSoup 做错了什么,还是 BeautifulSoup 源代码有误?我的原始代码的最小可执行版本:

from bs4 import BeautifulSoup
from bs4 import Comment
soup = BeautifulSoup('<p>This</p>Insert here:***<div id="apb">Stuff</div>')
div = soup.find(id="apb")
comment = Comment('APB section')
div.insert_before(comment)

这会产生回溯:

AttributeError                            Traceback (most recent call last)
<ipython-input-20-09e7eb15e6f2> in <module>()
  4 div = soup.find(id="apb")
  5 comment = Comment('APB section')
----> 6 div.insert_before(comment)
  7

C:\Users\bbrown\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\element.pyc in insert_before(self, predecessor)
353         # are siblings.
354         if isinstance(predecessor, PageElement):
--> 355             predecessor.extract()
356         index = parent.index(self)
357         parent.insert(index, predecessor)

C:\Users\bbrown\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\element.pyc in extract(self)
232     def extract(self):
233         """Destructively rips this element out of the tree."""
--> 234         if self.parent is not None:
235             del self.parent.contents[self.parent.index(self)]
236

C:\Users\bbrown\AppData\Local\Enthought\Canopy\User\lib\site-packages\bs4\element.pyc in __getattr__(self, attr)
673             raise AttributeError(
674                 "'%s' object has no attribute '%s'" % (
--> 675                     self.__class__.__name__, attr))
676
677     def output_ready(self, formatter="minimal"):

AttributeError: 'Comment' object has no attribute 'parent'

我正在使用 Python 2.7。我想我正在使用 beautifulsoup4 v4.3.2;这是 Canopy 包管理器通过访问 BeautifulSoup.__version__ 报告的版本导致 AttributeError .

我认为前面描述的错误可能是源代码中的错误的原因是我成功地添加了 5 行代码的变通方法:

comment.parent = None
comment.next_sibling = None
comment.next_element = None
comment.previous_sibling = None
comment.previous_element = None

我认为 Comment构造函数会将这些值设置为 None或者 element.py代码将测试属性是否存在,而不是测试是否与 None 相等.是我的错误还是 BeautifulSoup 源的问题?

最佳答案

这是一个相关的错误:

要么升级到当前最新的 beautifulsoup4 4.4.1,其中包含修复:

pip install beautifulsoup4 --upgrade

或者,应用 workaround Martijn 建议:

comment = soup.new_string('APB section', Comment)
div.insert_before(comment)

关于python - 在 BeautifulSoup 中插入新构造的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725704/

相关文章:

python - randrange() 函数如何工作?

python - Pandas 从剪贴板读取不规则数据

python - 函数可以是 Python 部分中的 kwargs 之一吗?

python - 当将 python 脚本作为 cron 选项卡运行时,如何启用本地模块?

python - 使用请求解析亚马逊上的产品标题

Python BeautifulSoup 没有抓取多个页面

python - `plt.style.context` 中的 `matplotlib` 可以用作 Python 3.6 中的 `decorator` 吗?

python - 源代码字符串不能包含空字节

python - 使用 Beautiful Soup 查找第三个出现的 `<p>` 标签

Python错误: TypeError: 'NoneType' object is not callable