前言
虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 “HTTP for Humans”,说明使用更简洁方便。
Requests 继承了urllib2的所有特性。Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。
开源地址:https://github.com/kennethreitz/requests
中文文档 API: http://docs.python-requests.org/zh_CN/latest/index.html
一、GET请求
1.1 最基本的GET请求
# 写法一: response = requests.get(\"http://www.baidu.com/\") # 写法二: # response = requests.request(\"get\", http://www.baidu.com/)
1.2 添加headers和查询参数
如果想添加 headers,可以传入headers参数来增加请求头中的headers信息。如果要将参数放在url中传递,可以利用 params 参数。
import requests kw = {\'wd\':\'长城\'} headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36\"} # params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode() response = requests.get(\"http://www.baidu.com/s?\", params = kw, headers = headers)
#查看响应内容,response.text 返回的是Unicode格式的数据 print response.text #<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer> .....
# 查看响应内容,response.content返回的字节流数据 print respones.content
# 查看完整url地址 print response.url # http://www.baidu.com/?wd=%E9%95%BF%E5%9F%8E
# 查看响应头部字符编码 print response.encoding # ISO-8859-1
# 查看响应码 print response.status_code # 200
二、POST请求
2.1 最基本的POST请求
response = requests.post(\"http://www.baidu.com/\", data = data)
2.2 传入data数据
对于 POST 请求来说,我们一般需要为它增加一些参数。那么最基本的传参方法可以利用 data 这个参数。
import requests formdata = { \"type\":\"AUTO\", \"i\":\"i love python\", \"doctype\":\"json\", \"xmlVersion\":\"1.8\", \"keyfrom\":\"fanyi.web\", \"ue\":\"UTF-8\", \"action\":\"FY_BY_ENTER\", \"typoResult\":\"true\" } url = \"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null\" headers={ \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\"} response = requests.post(url, data = formdata, headers = headers)
print response.text # {\"type\":\"EN2ZH_CN\",\"errorCode\":0,\"elapsedTime\":2,\"translateResult\":[[{\"src\":\"i love python\",\"tgt\":\"我喜欢python\"}]],\"smartResult\":{\"type\":1,\"entries\":[\"\",\"肆文\",\"高德纳\"]}}
# 如果是json文件可以直接显示 print response.json() # {u\'errorCode\': 0, u\'elapsedTime\': 0, u\'translateResult\': [[{u\'src\': u\'i love python\', u\'tgt\': u\'\\u6211\\u559c\\u6b22python\'}]], u\'smartResult\': {u\'type\': 1, u\'entries\': [u\'\', u\'\\u8086\\u6587\', u\'\\u9ad8\\u5fb7\\u7eb3\']}, u\'type\': u\'EN2ZH_CN\'}
© 版权声明
THE END
暂无评论内容