requests.get()函数接受一个要下载的 URL 字符串。通过在 requests.get()的返回
值上调用 type(),你可以看到它返回一个 Response 对象,其中包含了 Web 服务器对你的请求做出的响应。稍后我将更详细地解释 Response
对象,但现在请在交互式环境中输入以下代码,并保持计算机与因特网的连接:
>>> import requests
➊ >>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> type(res)
<class 'requests.models.Response'>
➋ >>> res.status_code == requests.codes.ok
True
>>> len(res.text)
178981
>>> print(res.text[:250])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
This eBook is for the use of anyone anywhere at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it under the terms
of the Proje
该 URL 指向一个文本页面,其中包含整部罗密欧与朱丽叶,它是由古登堡计划➊提供的。通过检查 Response 对象的 status_code
属性,你可以了解对这个网页的请求是否成功。如果该值等于 requests.codes.ok,那么一切都好➋(顺便说一下,HTTP协议中“OK”的状态码是
200。你可能已经熟悉 404 状态码,它表示“没找到”)。
如果请求成功,下载的页面就作为一个字符串,保存在 Response 对象的 text变量中。这个变量保存了包含整部戏剧的一个大字符串,调用 len(res.text)表明,它的长度超过 178000
个字符。最后,调用 print(res.text[:250])显示前 250 个字符。