我正在尝试从 http://book.libertorrent.com/ 获取数据,但目前我失败得很严重,因为响应中出现了一些额外的数据( header )。我的代码很简单:
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() 是空的。
有什么办法可以纠正响应吗?
最佳答案
让我们试试这个:
$ 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 header ,我猜这就是这里的响应解析器抛出的原因。
顺便说一下,python2 和 python3 在这里的行为不同:
- python2 似乎立即将此无效 header 之后的任何内容解释为内容
- python3 忽略所有标题并继续读取双换行符后的内容。由于 header 被忽略,传输编码也被忽略,因此内容长度被解释为正文的一部分。
所以最后的问题是服务器发送了无效的响应,应该在服务器端修复。
关于Python urllib 打开问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324109/