Mag*_*gie 3 python http python-requests
我需要登录并上传文件.我面临的问题是,登录页面与上传页面不同.如果我必须手动完成,我将登录(login.php)到该站点,然后导航到上传页面(uploader.php)以上传文件.这就是我写的:
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"
Run Code Online (Sandbox Code Playgroud)
我的代码显然没有按预期工作.登录部分工作正常但不上传部分.请问我该如何实现目标.
更新:
为了更深入地了解我的问题,我提供login.php并uploader.php提交详细信息:
的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>
Run Code Online (Sandbox Code Playgroud)
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)'>
Run Code Online (Sandbox Code Playgroud)
进行会话,然后使用该会话来完成您的请求 -
sessionObj = requests.session()
sessionOj.get(...) # Do whatever ...
Run Code Online (Sandbox Code Playgroud)
会话会保留您的cookie以用于将来的请求.
并使用用户名,密码的post参数作为登录所需的参数login.php,而不是auth用户名密码.
还可以使用files参数上传文件.所以最终的代码是 -
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4584 次 |
| 最近记录: |