2017-08-13 39 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