【问题标题】:lxml: Element is not a child of this nodelxml:元素不是该节点的子节点
【发布时间】:2025-12-30 04:00:07
【问题描述】:

我正在尝试更改以下 html 文档中 title 的值:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title id="title"></title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <app-root></app-root>
</body>
</html>

为了完成任务,我编写了以下使用 lxml 的 python 脚本:

from lxml.html import fromstring, tostring
from lxml.html import builder as E

html = fromstring(open('./index.html').read())
html.replace(html.get_element_by_id('title'), E.TITLE('TEST'))

但运行脚本后,我得到以下错误:

ValueError: 元素不是该节点的子节点。

应该是什么导致此错误?谢谢。

【问题讨论】:

  • &lt;title&gt;&lt;head 的子级,.replace(... 的第一个参数必须是&lt;title&gt; 的父级。

标签: python lxml


【解决方案1】:

“title”标签是“head”节点的子节点。在您的代码中,您在“html”节点上使用replace,该节点没有“标题”元素(不是直接),因此是ValueError

如果您在“头”节点上使用replace,您可以获得所需的结果。

html.find('head').replace(html.get_element_by_id('title'), E.TITLE('TEST'))

【讨论】:

  • 完美,我明白了。谢谢你的解释。
  • 哇,这真的很棘手。受您的启发,我最终使用了old_ele.getparent().replace(old_ele, new_ele)