使用 Python 'requests' 登录并上传文件 [英] Login and upload file using Python 'requests'

查看:27
本文介绍了使用 Python 'requests' 登录并上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要登录并上传文件.我面临的问题是,登录页面与上传页面不同.如果我必须手动执行,我将登录 (login.php) 到该站点,然后导航到上传页面 (uploader.php) 以上传文件.这是我写的:

I need to login and upload a file . The problem I am facing is, login page is different from uploading page. If I have to do it manually, I'll login (login.php) to the site and then navigate to the upload page (uploader.php) to upload the file. This what I have written:

import requests

url1='http://www.abc.com/login.php'
r = requests.post(url1, auth=('uname', 'pword'))
print r.status_code //msg:'200'

payload = {'upload':open('./tmp.txt')}
url2='http://www.abc.com/uploader.php'
r = requests.post(url2, data=payload)
print r.text //msg: "you must first login to upload the file"

我的代码显然没有按预期工作.登录部分工作正常,但没有上传部分.请问我怎样才能实现我的目标.

My code is obviously not working as expected. Login part is working correctly but not uploading part. Please how can I accomplish my goal.

更新:

为了更深入地了解我的问题,我提供了 login.phpuploader.php 文件详细信息:

To give more insight into my question, I am giving login.php and uploader.php file details:

login.php

<form method="POST" action="login.php" class="login">
<input type="text" name="username"></input>
<input type="password" name="password"></input>        
<input type="submit" value="Login"></input>

uploader.php

<form action='uploader.php' method='POST' id='form' class='upload' enctype="multipart/form-data" >
<input type='file' name='upload' id='file'></input>
<input type='button' value='Analyze' name='button' onclick='javascript: checkuploadform(false)'>

推荐答案

创建一个会话,然后使用该会话来处理您的请求 -

Make a session and then use that session to do your requests -

sessionObj = requests.session()
sessionOj.get(...) # Do whatever ...

会话会保留您的 cookie 以供将来请求使用.
并使用post参数作为用户名,密码作为参数在login.php中登录,而不是auth用户名密码.
还可以使用 files 参数上传文件.所以最终的代码是——

A session persists your cookies for future requests.
And use post parameters for username,password as the parameters are required to login in login.php , not auth username password.
Also use files parameter to upload files. So the final code is -

import requests

sessionObj = requests.session()
url1='http://www.abc.com/login.php'
r = sessionObj.post(url1, params={'username':'usernamehere' , 'password':'password here'})
print r.status_code //msg:'200'


filehandle = open('./tmp.txt')
url2='http://www.abc.com/uploader.php'
r = sessionObj.post(url2, data={},files = {'upload':filehandle})
print r.text

文档.

这篇关于使用 Python 'requests' 登录并上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆