【问题标题】:How to save web page as text file [Python]如何将网页保存为文本文件 [Python]
【发布时间】:2016-02-03 00:03:19
【问题描述】:

我想将网页(所有内容)保存为文本文件。 (好像您确实右键单击网页 -> “另存为” -> “另存为文本文件”,而不是作为 html 文件)

我已尝试使用以下代码:

import urllib2
url=''
page = urllib2.urlopen(url)
page_content = page.read()
file = open('file_text.txt', 'w')
f.write(page_content)
f.close()

我的目标是能够在没有 html 代码的情况下保存整个文本。 (例如我想读“è”而不是“&eacute”)

【问题讨论】:

标签: python web text save


【解决方案1】:

看看html2text 提到的elsewhere

import urllib2
import html2text
url=''
page = urllib2.urlopen(url)
html_content = page.read()
rendered_content = html2text.html2text(html_content)
file = open('file_text.txt', 'w')
file.write(rendered_content)
file.close()

【讨论】:

  • 嗨 pnovotnak,谢谢!我看到了库 html2text 但是当我“导入”时它返回一个错误。 import html2text ~ ImportError: No module named html2text 我在 Windows 上使用 python 2.7,我不明白如何添加库“html2text”以获得正确使用。 (我也尝试过使用 python 3.5,但我遇到了同样的问题)
  • 不用担心 :) 您需要安装它,因为它不是标准 Python 库的一部分。见这里:python-packaging-user-guide.readthedocs.org/en/latest/…
  • 我收到错误 TypeError: a bytes-like object is required, not 'str'rendered_content = html2text...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
相关资源
最近更新 更多