python-requests简单使用

Python-requests参考文档

https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests

1、get请求

def test_get(self):
r = requests.get("http://www.httpbin.org/get")
print(json.dumps(r.json(),indent=2))
logging.info(r.text)

2、post请求

携带请求数据data,设置代理  proxies,并且不进行验证

class Test_request(object):
    url = "https://www.cnblogs.com/ychun/default.html?page=2"
def test_post(self):
        r=requests.post(self.url,
                        data={"a":"a11","b":"eeeeee"},
                        proxies={"https":"https://192.168.109.2:8888",
                                 "http":"http://192.168.109.2:8888"
                                 },
                        verify=False
                        )
        print(r.url)

3、post请求,发送json数据

 def test_json(self):
        r=requests.post(self.url,
                        json={"a":"a11","b":"eeeeee"},
                        proxies={"https":"https://192.168.109.2:8888",
                                 "http":"http://192.168.109.2:8888"
                                 },
                        verify=False
                        )
        print(r.url)

 4、修改请求头


def test_header(self):
r = requests.get(self.url,
params={"a": "a11", "b": "eeeeee"},
headers={"User-Agent": "a11", "Accept": "application/json, text/javascript, */*; q=0.01"},
proxies={"https": "https://192.168.109.2:8888",
"http": "http://192.168.109.2:8888"
},
verify=False
)
print(r.url)

 5、构建数据、请求雪球

请求头、cookie分别在文件header.txt与cookie.txt中

def  test_xueqie(self):
url='https://stock.xueqiu.com/v5/stock/portfolio/stock/list.json'
# 取出文件中的header
header_file = open('./header.txt','r')
header_dict={}
for f in header_file:
ss = f.split(": ")
header_dict[ss[0]]=ss[1].split(" ")[0]
# 取出文件中的cookie
file = open('./cookie.txt','r')
cookie_dict={}
for f in file:
ss = f.split("=")
cookie_dict[ss[0]]=ss[1].split(" ")[0]
# 发送请求
r = requests.get(url,cookies=cookie_dict,
params={"size":"1000","category":"1","pid":"-1"},
headers=header_dict
)
# 打印结果
print(json.dumps(r.json(),indent=2))
#断言
assert r.json()['data']['pid'] == -1

数据

 请求头获取

原文地址:https://www.cnblogs.com/ychun/p/14402236.html