前言

虽然python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 api 使用起来让人感觉不太好,而 requests 自称 “http for humans”,说明使用更简洁方便。

requests 继承了urllib2的所有特性。requests支持http连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 url 和 post 数据自动编码。

开源地址:

中文文档 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'}

到此这篇关于详解python requests模块的文章就介绍到这了,更多相关python requests模块内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!