【问题标题】:Problems with Python 2.6 and 3.2 urlopen Routines on WindowsWindows 上 Python 2.6 和 3.2 urlopen 例程的问题
【发布时间】:2011-11-15 00:02:12
【问题描述】:

之前在python 2.6中,我已经大量使用了urllib.urlopen来捕获 网页内容,然后稍后处理我收到的数据。现在,这些例程以及我尝试用于 python 3.2 的新例程正在运行到似乎只是 Windows 的东西(甚至可能只是 Windows 7 的问题)。

在 windows 7 上使用以下代码与 python 3.2.2 (64) ...

import urllib.request

fp = urllib.request.urlopen(URL_string_that_I_use)

string = fp.read()
fp.close()
print(string.decode("utf8"))

我收到以下消息:

Traceback (most recent call last):
  File "TATest.py", line 5, in <module>
    string = fp.read()
  File "d:\python32\lib\http\client.py", line 489, in read
    return self._read_chunked(amt)
  File "d:\python32\lib\http\client.py", line 553, in _read_chunked
    self._safe_read(2)      # toss the CRLF at the end of the chunk
  File "d:\python32\lib\http\client.py", line 592, in _safe_read
    raise IncompleteRead(b''.join(s), amt)
http.client.IncompleteRead: IncompleteRead(0 bytes read, 2 more expected)

改用下面的代码...

import urllib.request

fp = urllib.request.urlopen(URL_string_that_I_use)
for Line in fp:
    print(Line.decode("utf8").rstrip('\n'))
fp.close()

我获得了相当多的网页内容,但随后捕获的其余部分 被...阻挠了

Traceback (most recent call last):
  File "TATest.py", line 9, in <module>
    for Line in fp:
  File "d:\python32\lib\http\client.py", line 489, in read
    return self._read_chunked(amt)
  File "d:\python32\lib\http\client.py", line 545, in _read_chunked
    self._safe_read(2)  # toss the CRLF at the end of the chunk
  File "d:\python32\lib\http\client.py", line 592, in _safe_read
    raise IncompleteRead(b''.join(s), amt)
http.client.IncompleteRead: IncompleteRead(0 bytes read, 2 more expected)

尝试阅读另一页会产生...

Traceback (most recent call last):
  File "TATest.py", line 11, in <module>
    print(Line.decode("utf8").rstrip('\n'))
  File "d:\python32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x92' in position
21: character maps to <undefined>

我确实相信这是一个 Windows 问题,但可以让 python 更强大以处理 是什么原因造成的?在 Linux 上尝试类似代码(2.6 版代码)时,我们没有遇到问题。有没有解决的办法?我还发布到 gmane.comp.python.devel 新闻组

【问题讨论】:

    标签: python urllib python-2.6 python-3.2


    【解决方案1】:

    您正在阅读的页面似乎被编码为cp1252

    import urllib.request
    
    fp = urllib.request.urlopen(URL_string_that_I_use)
    
    string = fp.read()
    fp.close()
    print(string.decode("cp1252"))
    

    应该可以。

    There are many 指定内容字符集的方法,但对于大多数页面来说,使用 HTTP 标头就足够了:

    import urllib.request
    
    fp = urllib.request.urlopen(URL_string_that_I_use)
    
    string = fp.read().decode(fp.info().get_content_charset())
    fp.close()
    print(string)
    

    【讨论】:

    • 感谢 Cees。好久没看这个了,现在才发现你已经回答了。我相信它在未来会很有价值。
    猜你喜欢
    • 2013-09-16
    • 2018-03-24
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 2011-08-24
    • 2014-07-19
    • 1970-01-01
    • 2011-01-06
    相关资源
    最近更新 更多