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
数据
请求头获取
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~