引言:网络有代理时,使用requests.get()等请求,会提示超时。在请求中加入代理设置,则可以正常使用。
一、问题截图如下:
E requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='xxxx.com', port=443): Max retries exceeded with url: /usersLogin/login (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x000001E3772791E0>, 'Connection to 10.37.84.94 timed out. (connect timeout=None)'))
二、原因:
我是在公司内网环境访问外网域名,在连接的时候报错,无法连接,超时;后来定位到是由于公司的网络拦截导致,需要设置代理
三、Requests设置代理:
class TestLogin(CommonUtil):
@pytest.mark.parametrize('caseinfo',read_yaml_testcase('testcase/test_login.yaml'))
def test_login_01(self,caseinfo):
print("\n测试01号登录成功")
print(caseinfo)
name = caseinfo['name']
method = caseinfo['request']['method']
url = caseinfo['request']['url']
data = caseinfo['request']['data']
header= caseinfo['request']['headers']
validate = caseinfo['validate']
proxy = {'http':'http://username:password@ip:port',
'https': 'https://username:password@ip:port'
}
res = RequestsUtil().send_all_request(method= method, url=url,headers=header, data=data,proxies=proxy)
1、设置http和https代理,根据接口是http请求或者是https请求,进行对应的设置(也可以两个都写上)
2、ip:port,代理服务器的ip和端口,由代理服务器来将请求发送给目标服务器
3、username:password:代理网络的用户名和密码,有些需要填,有些不需要填,如果不知道的话,可以先不填试试
# 1:普通的代理
proxies = {"http":"http://12.34.56.79:9527",
"https":"https://12.34.56.79:9527"}
res = requests.get(url="http://www.baidu.com",proxies=proxies)
print(res.content.decode("utf-8"))
# 2:携带登录的用户名和密码
proxies1 = {"http":"http://用户名:密码@12.34.56.79:9527",
"https":"https://用户名:密码@12.34.56.79:9527"
}
res = requests.get(url="http://baidu.com",proxies=proxies1)
print(res.content.decode("utf-8"))