用 requests 模块从 Web 下载文件

用 requests 模块从 Web 下载文件

       requests 模块让你很容易从 Web 下载文件,不必担心一些复杂的问题,诸如网络错误、连接问题和数据压缩。requests 模块不是 Python 自带的,所以必须先安装。

       requests.get()函数接受一个要下载的 URL 字符串。通过在 requests.get()的返回

值上调用 type(),你可以看到它返回一个 Response 对象,其中包含了 Web 服务器对

你的请求做出的响应。

       >>> 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 个字符。

原文地址:https://www.cnblogs.com/cqkangle/p/10508319.html