【问题标题】:What is the proper method for reading and writing HTML/XML (byte string) with Python and lxml and etree?用 Python 和 lxml 和 etree 读写 HTML/XML(字节字符串)的正确方法是什么?
【发布时间】: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


    【解决方案1】:

    这可以在几行代码中使用 lxml 完成,而无需使用 open.write 方法是正是你想要做的事情:

    # parse using file name which is the also the recommended way.
    tree = html.parse("C:/Users/mhurley/Portable_Python/notebooks/View_Custom_Report.html")
    # call write on the tree
    tree.write("C:/Users/mhurley/Portable_Python/notebooks/Pretty.html", pretty_print=True, encoding="utf=8")
    

    还有file_text = ''.join(file.readlines())file_text = file.read()完全一样

    【讨论】:

      【解决方案2】:

      您错过了从 etree 的 tostring 方法获取字节,并且在将(字节字符串)写入文件时需要考虑到这一点。像这样在open 函数中使用b 开关,忘记str() 转换:

      with open('Pretty.html', 'wb') as file:
          #write the pretty XML to a file
          file.write(document)
      

      附录

      尽管这个答案解决了眼前的问题并教授了字节串,但Padraic Cunninghamsolution 是将 lxml etree 写入文件的更清洁、更快捷的方法。

      【讨论】:

      • 我也注意到了这一点,但问题仍然存在:当我将其写入文件时,如何让它不“变得有趣”?
      • 太棒了!谢谢!我不知道 'wb' 是写入文件的有效模式。这非常有效。
      • ...这可能也解释了为什么我的输出文件以“b”开头并完全包含在一组单引号中。我觉得这很奇怪,但我认为它没有意义。
      猜你喜欢
      • 1970-01-01
      • 2021-11-14
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      相关资源
      最近更新 更多