【发布时间】:2016-10-13 22:09:06
【问题描述】:
编辑:现在问题已经解决,我意识到它更多地与正确读取/写入字节字符串有关,而不是 HTML。希望这会让其他人更容易找到这个答案。
我有一个格式不正确的 HTML 文件。我想使用 Python 库来使其整洁。
看起来应该像下面这样简单:
import sys
from lxml import etree, html
#read the unformatted HTML
with open('C:/Users/mhurley/Portable_Python/notebooks/View_Custom_Report.html', 'r', encoding='utf-8') as file:
#write the pretty XML to a file
file_text = ''.join(file.readlines())
#format the HTML
document_root = html.fromstring(file_text)
document = etree.tostring(document_root, pretty_print=True)
#write the nice, pretty, formatted HTML
with open('C:/Users/mhurley/Portable_Python/notebooks/Pretty.html', 'w') as file:
#write the pretty XML to a file
file.write(document)
但是这段代码抱怨file_lines 不是字符串或类似字节的对象。好吧,我想函数不能接受列表是有道理的。
但是,它是“字节”而不是字符串。没问题,str(document)
但是我得到的 HTML 中充满了 '\n' 而不是换行符......它们是一个斜线,后跟一个 en。结果中并没有实际的回车,它只是一长行。
我尝试了许多其他奇怪的事情,例如指定编码、尝试解码等。但都没有产生预期的结果。
读写这种(非ASCII是正确的术语吗?)文本的正确方法是什么?
【问题讨论】:
标签: html python-3.x character-encoding lxml elementtree