如何下载和读取带有通用换行符的 URL?

发布于 2024-12-17 06:25:45 字数 233 浏览 4 评论 0原文

我将 urllib.urlopen 与 Python 2.7 一起使用,但我需要处理下载的 HTML 文档及其包含的换行符(在

 元素内)。

urllib 文档 表明 urlopen 不会使用通用换行符。我该怎么做?

I was using urllib.urlopen with Python 2.7, but I need to process the downloaded HTML document and its contained newlines (within a <pre> element).

The urllib docs indicates urlopen will not use universal newlines. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

网名女生简单气质 2024-12-24 06:25:45

除非 HTML 文件已经在您的磁盘上,否则 urlopen() 将正确处理所有格式的换行符(\n\r\n\r) 在您想要解析的 HTML 文件中(即将它们转换为 \n),根据 urllib 文档

“如果 URL 没有方案标识符,或者具有 file: 作为其方案标识符,则会打开本地文件(没有通用换行符)”

例如

>>> from urllib import urlopen
>>> urlopen("http://****.com/win_new_lines.htm").read()
'line 1\nline 2\n\n\nline 3'
>>> urlopen("http://****.com/unix_new_lines.htm").read()   
'line 1\nline 2\n\n\nline 3'

Unless the HTML file is already on your disk, urlopen() will handle correctly all formats of newlines (\n, \r\n and \r) in the HTML file you want to parse (that is it will convert them to \n), according to the urllib docs:

"If the URL does not have a scheme identifier, or if it has file: as its scheme identifier, this opens a local file (without universal newlines)"

E.g.

>>> from urllib import urlopen
>>> urlopen("http://****.com/win_new_lines.htm").read()
'line 1\nline 2\n\n\nline 3'
>>> urlopen("http://****.com/unix_new_lines.htm").read()   
'line 1\nline 2\n\n\nline 3'
绅士风度i 2024-12-24 06:25:45

当您处理 pre 标记的内容时,请使用 splitlines 规范行结束符:

'\n'.join(contents.splitlines())

When you process the contents of the pre tags, use splitlines to normalize the line-endings:

'\n'.join(contents.splitlines())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文