设置http代理,然后在get或者post的时候提供proxies参数。
import requests
proxies = {
"http": "http://172.1.1.7:1080",
"https": "http://172.1.2.7:1080",
}
requests.get("http://www.baidu.com", proxies=proxies)
如果代理需要http 基本认证,那么可以按照如下的方式设置代理:
proxies = { "http":"http://username:passward@172.1.2.7:1080"}
pac 是proxy auto configuration的缩写,也就是自动配置代理,在很多公司连接外网的时候,采用的都是pac代理。 在使用python 进行web接口测试的时候,如果遇到pac 代理的情况,那么需要用pypac 模块来实现网络连接.pypac 模块会可以解析pac配置文件,一个比较简单的使用步骤如下:
#!/usr/bin/env python
import pypac
pac_file=pypac.get_pac("http://XXX.com/xxx.pac") #Get the PAC file object
PAC_SESSION=pypac.PACSession(pac_file) #Get the PAC SESSION object. Similar with reqeusts.session object.
response=PAC_SESSION.get("https://www.baidu.com/")
print(response.text) #Check the response contents.
虽然大多数https网站的证书都是权威机构签发,不会有验证问题,但是公司内部的网站,可能是自签发证书,这时候,如果没有添加信任的话,那么一般会出现如下的报错: "requests.exceptions.SSLError: ......", 这时候可以在get/post的request上加上 verify=false的参数来解决,比如上述的: response=PAC_SESSION.get("https://my.site.com/", verify=False), 如果是verify=True, 那么表示要进行证书的验证,默认是verify=True. 上述方式其实并不推荐,最好的做法是信任证书,然后就没有问题了. 不过上述是最简单的方式了.
虽然python可以通过 在请求时候添加 verify=False 来跳过证书的验证过程,但是 如果我们跳过证书的验证,那么python 会给出如下的警告: ** InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3......**, 这时候要disable 这个alerts, 用如下的方式:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) #Disable the SSL warning.
在实际的环境中,遇到重定向是再正常不过的事情了,pyhton 的requests 库会自动处理重定向,也就是说,当我们用get方法的时候,redirect 自动执行,通常返回的是重定向后的结果,我们可以在get的时候添加 allow_redirects=False 参数,从而避免自动重定向。
~# cat my.py
#/usr/bin/env python
import requests
r=requests.get("https://cloud.tencent.com/qccomponent/login/api.js") #默认情况下,自动处理redirect .
print(r.status_code)
~# python my.py
200
#################禁止redirect##############################
~# cat my.py
#/usr/bin/env python
import requests
r=requests.get("https://cloud.tencent.com/qccomponent/login/api.js",allow_redirects=False) #添加allow_redirects=False 来禁止重定向。
print(r.status_code) #返回状态为302, 表示重定向.
~# python my.py
302
那么重定向之后的URL是什么呢? 这个可以通过response的headers 信息里面一个key 为location的值找到。如下python的示例用于获取重定先向之后的URL:
$ cat my.py
#/usr/bin/env python
import requests,json
r=requests.get("https://cloud.tencent.com/qccomponent/login/api.js",allow_redirects=False)
print(r.headers["location"])
$ python my.py #运行得到跳转后的地址
https://imgcache.qq.com/qcloud/main/scripts/release/common/login/api.7e9f7a8c93ec5647a3a2.js?max_age=31536000
如果不通过抓包,我们很难知道是否发生了跳转,而在每个浏览器中一般都是“development tool” 或者“development plugin”, 一般是F12键,打开后,切换到“Network” tab,然后就可以看到了.事实上,如果要做web 接口测试,该工具的使用是必不可少的.
get请求一般是不带参数的,但是也可以带参数,其所带的参数是会出现在URL中的, post请求的参数是不会出现在URL中的,所以当我们传递用户名密码等信息的时候,都是采用post方式,而不是get.