Python urllib开放式issu

2024-04-27 16:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从获取数据http://book.libertorrent.com/,但目前我失败得很厉害,因为响应中出现了一些额外的数据(头)。我的代码非常简单:

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

read()返回:

^{pr2}$

而且回复信息()为空。在

有什么方法可以正确回答吗?在


Tags: 数据代码comhttpreadresponsehtmllogin
1条回答
网友
1楼 · 发布于 2024-04-27 16:47:59

让我们试试这个:

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

所以最后问题是服务器发送的响应无效,这应该在服务器端得到解决。在

相关问题 更多 >