Reputation: 3506
I'm trying to change the value of title within the following html document:
<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>
I wrote the following python script which uses lxml, in order to accomplish the task:
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'))
But after running the script, I get the following error:
ValueError: Element is not a child of this node.
What's supposed to cause this error? Thank you.
Upvotes: 4
Views: 2704
Reputation: 15376
The 'title' tag is a child of the 'head' node. In your code you use replace
on the 'html' node, which has no 'title' elements (not directly), hence the ValueError
.
You can get the desired results if you use replace
on the 'head' node.
html.find('head').replace(html.get_element_by_id('title'), E.TITLE('TEST'))
Upvotes: 5