Login and upload file using Python 'requests'

后端 未结 1 750
离开以前
离开以前 2021-01-06 14:31

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

1条回答
  •  一整个雨季
    2021-01-06 14:50

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

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

    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
    

    Docs.

    0 讨论(0)
提交回复
热议问题