2017-08-13 40 views
0

我有一个HTML页面,我想使用python脚本进行编辑。我正在使用Dominate使用python 3.5.2编辑HTML页面并占主导地位

这是一个准系统示例。

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

简单的HTML正确吗?
这里的python脚本:

import dominate 
from dominate.tags import * 

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

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

我收到以下错误,当我运行此脚本。

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

我的HTML确实有'头'。

如何使用支配来编辑我的文件?

回答

0

原因是什么open()函数返回没有属性head

您应该使用Dominate库中的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) 

希望它能帮助!

+0

它确实有效,但由于某种原因弄乱了整个文档。另外,它不会改变原来的HTML文件 – YaddyVirus

+0

它把我在身体里面的'标签'标签中的h1标签 – YaddyVirus

+0

它清除了我的index.html文件 – YaddyVirus