您的位置: 网站首页> requests爬虫> 当前文章

requests上传单个文件

老董-我爱我家房产SEO2021-11-11152围观,132赞

  HTTP协议中没有规定post提交数据必须使用什么数据格式,服务端根据请求头中的Content-Type字段来获取提交方式然后对数据进行解析。在html中的form表单中enctype属性有3种设置方式:

 <form action="url地址" enctype="application/x-www-form-urlencoded" method="POST">
<form action="url地址" enctype="multipart/form-data" method="POST"> 上传文件的设置
<form action="url地址" enctype="text/plain" method="POST">

  在form表单中如果要上传文件,就必须设置enctype="multipart/form-data",我们可以写1个简单上传文件界面:

<form action="https://www.baidu.com/index.php" enctype="multipart/form-data" method="POST">
  <input name="file" type="file" id="file">  <!--选择文件按钮-->
  <input type="submit" value="提交"> <!--提交按钮-->
</form> 

  浏览器上传文件需要点击-选择文件-上传,文件也是一种数据,在requests中上传文件提供了对应的参数来实现:

url = 'http://httpbin.org/post'
files = {'file': open('111.xlsx', 'rb')}
r = requests.post(url, files=files)
# 看请求头
print(r.request.headers)

  也可以显式地设置文件名,文件类型再加上其他请求头:

headers = {
'User-Agent':'www.python66.com'
}
url = 'http://httpbin.org/post'
files = {'file': ('111.xlsx', open('111.xlsx', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files,headers=headers)
# 看请求头
print(r.request.headers)
{'User-Agent': 'www.python66.com', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '11807', 'Content-Type': 'multipart/form-data; boundary=9a49be06a88a565067e373eaf887bd28'}

  上述结果中可以看到请求头里面多了1个字段:'Content-Type': multipart/form-data,这代表是上传文件。而后面boundary=9a49be06a88a565067e373eaf887bd28是随机字符串分隔符,是请求头的一部分,这个东西可以忽略,没有特别需要理解的东西。

  我们知道上传的是1个excel文件,但是不一定知道指定文件类型为application/vnd.ms-excel,如果不知道怎么指定文件类型那就不指定,大多数情况下也没事。如果一定要指定可以先手动抓包看一下浏览器上传文件时请求头信息,从那里面寻找有用的信息拿来用。

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    requests上传单个文件文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200