繁体   English   中英

Python urllib开放问题

[英]Python urllib open issue

我正在尝试从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()是空的。

有没有办法纠正反应?

我们试试这个:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM