【问题标题】:Python urllib open issuePython urllib 开放问题
【发布时间】:2012-11-10 17:06:44
【问题描述】:

我正在尝试从 http://book.libertorrent.com/ 获取数据,但目前我失败了,因为响应中出现了一些额外的数据(标题)。我的代码很简单:

response = urllib.urlopen('http://book.libertorrent.com/login.php')
f = open('someFile.html', 'w')
f.write(response.read())

read() 返回:

Date: Fri, 09 Nov 2012 07:36:54 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Cache-Control: no-cache, pre-check=0, post-check=0
Expires: 0
Pragma: no-cache
Set-Cookie: bb_test=973132321; path=/; domain=book.libertorrent.com
Content-Language: ru

1ec0
...Html...
0

response.info() 为空。

有什么方法可以纠正反应吗?

【问题讨论】:

  • 在 response.read() 之后,response.getcode() 说了什么?在我的 Mac 上,response.read() 返回 html,而 .getcode() 返回 200,这没问题(成功)。
  • 您的方法通常有效;当我在那个网站上尝试时,我遇到了同样的问题......
  • 我也是,有趣的是它适用于 Python 3。

标签: python urllib


【解决方案1】:

让我们试试这个:

$ echo -ne "GET /index.php HTTP/1.1\r\nHost: book.libertorrent.com\r\n\r\n" | nc book.libertorrent.com 80 | head -n 10
HTTP/1.1 200 OK
WWW
Date: Sat, 10 Nov 2012 17:41:57 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Content-Language: ru

1f57
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html dir="ltr">

看到第二行的“WWW”了吗?这不是有效的 HTTP 标头,我猜这就是这里抛出响应解析器的原因。

顺便说一下,python2 和 python3 在这里的行为不同:

  • python2 似乎会立即将此无效标头之后的任何内容解释为内容
  • python3 忽略所有标题并继续读取双换行符后的内容。因为标头被忽略,所以传输编码也是如此,因此内容长度被解释为正文的一部分。

所以最终问题是服务器发送的响应无效,应该在服务器端修复。

【讨论】:

  • 我在 Python3 上尝试了这段代码,结果比 Python2 好,头文件存在于 info() 中。现在响应看起来像: 1ec0 ...Html... 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多