使用python3.5.2和Domin编辑HTML页面

2024-09-28 20:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个HTML页面,我想用python脚本编辑它。我正在使用Dominate

这是一个简单的例子。在

<html>
<head>
  <title>asdjasda</title>
</head>
<body>
  <h1>THIS IS A TEST</h1>
</body>
</html>

简单的HTML对吗?
下面是python脚本:

^{pr2}$

运行此脚本时,出现以下错误。在

Traceback (most recent call last):  
  File "script.py", line 6, in <module>  
    with page.head:  
AttributeError: '_io.TextIOWrapper' object has no attribute 'head'

我的HTML确实有一个“头”。在

如何使用dominate编辑我的文件?在


Tags: test脚本编辑titleishtmlbody页面
1条回答
网友
1楼 · 发布于 2024-09-28 20:49:29

原因是open()函数返回的内容没有head属性。在

您应该使用支配库中的document。在

试试这个:

page = open('index.html','r',encoding='utf-8')
page_str = page.read()

doc = dominate.document(page_str)

with doc.head:
    link(rel='stylesheet', href='tts.css')

print(doc)

希望有帮助!在

相关问题 更多 >