Python进阶篇---网络编程

本文介绍使用Python进行网络编程的方法,涵盖GET和POST请求处理、JSON数据交互、Cookie与Header操作、文件下载与上传等功能,并提供详实的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网络编程,主要是引入urllib模块中的urlopen用法和urlencode用法

from urllib.request import urlopen

from urllib.parse import urlencode

import requests

1)get请求

         url = 'http://118.24.3.40/api/user/stu_info'

         方法一:

                res = urlopen(url)   #发送get请求

                print(res.read().decode())

         方法二:

                res = request.get(url,params = {'stu_name':'小黑'})     #发送get请求

                print(res.json())    #直接把返回结果转成字典

2)post请求

         url2 = 'http://118.24.3.40/api/user/login'

         方法一:

                data = {'username':'niuhanyang','passwd':'123456'}

                res = urlopen(url2,urlencode(data).encode())    #发送post请求

                print(res.read().decode())

        方法二:

               data = {'username':'niuhanyang','passwd':'123456'}

               res = request.post(url2,data = data)

               print(res.json)

3)入参是json格式的

         url3 = 'http://118.24.3.40/api/user/add_stu'

         data = {"name":"wwww","grade":"spz","phone","15500000000","sex":"男","age":"18","addr":"北京市朝阳区"}

         res = request.post(url3,json = data)

         print(res.json())

4)cookie类型

           url4 = 'http://118.24.3.40/api/user/gold_add'

           data = {'stu_id':15,'gold':200}

           cookie = {'niuhanyang':'xxxxxxxx'}

           res = request.post(url4,data = data,cookies = cookie)

           print(res.json)

5)header格式

        url5 = 'http://118.24.3.40/api/user/all_stu'

        header = {'Referer':'http://api.nnzhp.cn/'}

        res = request.get(url5,headers = header)

        print(res.json())

6)下载文件

         url6 = 'http://qiniuuwmp3.changba.com/234234.mp3'

         res = request.get(url6,verify = False)    #如果请求接口是https的,需要加上verify = False

         print(res.text)

         print(res.content)   #返回的就是二进制

         with open('aaa.mpe','wb') as fw:

               fw.write(res.content)

         print(res.cookie)    #获取到返回的所有cookie

         print(res.headers)    #获取到所有返回的header

7)上传图片

       url7 = 'http://118.24.3.40/api/file/file_upload'

       data = {'file':open('D:\pic\aaa.jpeg','rb')}

       res = request.post(url7,files = data)

       print(res.json)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值