• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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("\n")[0]
# 取出文件中的cookie
file = open('./cookie.txt','r')
cookie_dict={}
for f in file:
ss = f.split("=")
cookie_dict[ss[0]]=ss[1].split("\n")[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

数据

 

 请求头获取

 

posted on 2021-02-14 19:00  yxchun  阅读(125)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3