4

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

response = urllib.urlopen('http://book.libertorrent.com/login.php')
f = open('someFile.html', 'w')
f.write(response.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()是空的。

有没有办法纠正反应?

4

1 回答 1

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 忽略所有标题并继续读取双换行符后的内容。因为标头被忽略,所以传输编码也是如此,因此内容长度被解释为正文的一部分。

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

于 2012-11-10T17:55:23.407 回答