【问题标题】:Editing HTML page using python 3.5.2 and Dominate使用 python 3.5.2 和 Dominate 编辑 HTML 页面
【发布时间】:2017-08-13 11:09:38
【问题描述】:

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

这是一个简单的例子。

<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 确实有一个“头”。

如何使用操控来编辑我的文件?

【问题讨论】:

  • Dominate 不是 HTML 解析器。它严格用于创建新文档,而不是解析现有的 html 文件。你需要类似crummy.com/software/BeautifulSoup
  • @Knio 是的......经过几次尝试后,我放弃了 Dominate 并开始改用 BeautifulSoup。艰难地学会了它
  • 有点令人困惑的是,有 Python 包 github.com/Knio/dominate(恕我直言,这是一个很棒的包)和 Nodejs 包 github.com/ryanmorr/dominate,它是一个解析器。

标签: python html python-3.5 dominate


【解决方案1】:

原因是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)

希望对你有帮助!

【讨论】:

  • 它确实有效,但由于某种原因弄乱了整个文档。此外,它不会对原始 HTML 文件进行任何更改
  • 它将我在正文中的h1标签放在title标签内
  • Dominate 不是 HTML 解析器。此代码将原始 html 转储到新主控文档的标题参数中。
猜你喜欢
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多