requests
模块很容易从Web下载文件,
不必担心一些复杂的问题,诸如网络错误、
连接问题和数据压缩。 requests
模块不是
Python自带的,所以必须先安装。通过命令行,
运行 pip install requests
。
编写 requests
模块是因为Python的 urllib2
模块用起来太复杂。
如果需要从Web下载东西,使用 requests
模块就好了。
接下来,做一个简单的测试,确保 requests
模块已经正确安装。
在交互式环境中输入以下代码:
import requests
import requests
res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
type(res)
requests.models.Response
res.status_code == requests.codes.ok
True
len(res.text)
159503
print(res.text[ :250])
The Project Gutenberg eBook of The Tragedy of Romeo and Juliet This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give
该 URL 指向一个文本页面,其中包含整部罗密欧与朱丽叶,
它是由古登堡计划提供的。
通过检查 Response
对象的 status_code
属性,可以了解对这个网页的请求是否
成功。如果该值等于 requests.codes.ok
,那么一切都好
(顺便说一下,HTTP协议中“OK”的状态码是200。
可能已经熟悉404状态码,它表示“没找到”)。
如果请求成功,下载的页面就作为一个字符串,保存在
Response
对象的 text
变量中。这个变量保存了
包含整部戏剧的一个大字符串,调用 len(res.text)
表明,
它的长度超过178000个字符。最后,
调用 print(res.text[:250])
显示前250个字符。
检查错误
正如所看到的, Response
对象有一个 status_code
属性,
可以检查它是否等于 requests.codes.ok
,了解下载是否成功。
检查成功有一种简单的方法,
就是在 *Response
对象上调用 raise_for_status()
方法。
如果下载文件出错,这将抛出异常。如果下载成功,就什么也不做。
在交互式环境中输入以下代码:
# res = requests.get('http://inventwithpython.com/page_that_does_not_exist')
# res.raise_for_status()
raise_for_status()
方法是一种很好的方式,确保程序在下载失败时停止。
这是一件好事:希望程序在发生未预期的错误时,马上停止。
如果下载失败对程序来说不够严重,可以用 try
和 except
语句将 raise_for_status()
代码行包裹起来,
处理这一错误,不让程序崩溃。
# res = requests.get('http://inventwithpython.com/page_that_does_not_exist')
# try:
# res.raise_for_status()
# except Exception as exc:
# print('There was a problem: %s' % (exc))
raise_for_status()
方法调用导致程序输出以上内容。
总是在调用 requests.get()
之后再调用 raise_for_status()
。
希望确保下载确实成功,再让程序继续。