您在这里:首页 > 深入 Python > HTTP Web 服务 > 设置 User-Agent | << >> | ||||
深入 Python从 Python 新手到专家 |
改进 HTTP Web 服务客户端的第一步是使用 User-Agent 正确标识自己。为此,您需要超越基本的 urllib 并深入了解 urllib2。
>>> import httplib >>> httplib.HTTPConnection.debuglevel = 1>>> import urllib2 >>> request = urllib2.Request('http://diveintomark.org/xml/atom.xml')
>>> opener = urllib2.build_opener()
>>> feeddata = opener.open(request).read()
connect: (diveintomark.org, 80) send: ' GET /xml/atom.xml HTTP/1.0 Host: diveintomark.org User-agent: Python-urllib/2.1 ' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Wed, 14 Apr 2004 23:23:12 GMT header: Server: Apache/2.0.49 (Debian GNU/Linux) header: Content-Type: application/atom+xml header: Last-Modified: Wed, 14 Apr 2004 22:14:38 GMT header: ETag: "e8284-68e0-4de30f80" header: Accept-Ranges: bytes header: Content-Length: 26848 header: Connection: close
![]() |
如果您仍然打开了上一节示例中的 Python IDE,则可以跳过此步骤,但这会启用 HTTP 调试,以便您可以查看实际通过网络发送的内容以及返回的内容。 |
![]() |
使用 urllib2 获取 HTTP 资源是一个三步过程,原因很快就会清楚。第一步是创建一个 Request 对象,该对象获取您最终要检索的资源的 URL。请注意,此步骤实际上还没有检索任何内容。 |
![]() |
第二步是构建一个 URL 打开器。这可以使用任意数量的处理程序,这些处理程序控制如何处理响应。但是,您也可以构建一个没有任何自定义处理程序的打开器,这就是您在这里所做的。本章稍后,当您探索重定向时,您将看到如何定义和使用自定义处理程序。 |
![]() |
最后一步是告诉打开器使用您创建的 Request 对象打开 URL。从打印的所有调试信息中可以看出,此步骤实际上检索了资源并将返回的数据存储在 feeddata 中。 |
>>> request<urllib2.Request instance at 0x00250AA8> >>> request.get_full_url() http://diveintomark.org/xml/atom.xml >>> request.add_header('User-Agent', ... 'OpenAnything/1.0 +https://diveintopythonbook.pythonlang.cn/')
>>> feeddata = opener.open(request).read()
connect: (diveintomark.org, 80) send: ' GET /xml/atom.xml HTTP/1.0 Host: diveintomark.org User-agent: OpenAnything/1.0 +https://diveintopythonbook.pythonlang.cn/
' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Wed, 14 Apr 2004 23:45:17 GMT header: Server: Apache/2.0.49 (Debian GNU/Linux) header: Content-Type: application/atom+xml header: Last-Modified: Wed, 14 Apr 2004 22:14:38 GMT header: ETag: "e8284-68e0-4de30f80" header: Accept-Ranges: bytes header: Content-Length: 26848 header: Connection: close
<< 调试 HTTP Web 服务 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
处理 Last-Modified 和 ETag >> |