Chan
Chan

Reputation: 4301

How to upload file using Requests

I can use Selenium to upload a file as

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(r'https://www.example.com')
a = driver.find_element_by_xpath("//input[@type='file']")
a.send_keys(r'C:\abc.jpg')
b =  driver.find_element_by_xpath("//output[@id='result']").text

The above code works well.

Now, I want to use Requests to the same job. I tried to search on the web and implement the code. But I cannot get the result.

import requests
from lxml import html

a = requests.get(r'https://www.example.com')
tree = html.fromstring(a.text)
b = tree.xpath("//input[@type='file']")
b.append(r'C:\abc.jpg')#Is it correct?

The html code is as follows:

<div id="test" class="abc def ghi">
    <div class="xyz def ghi">
        Drag or<br class="def ghi">Click to input file
    </div>
    <div class="pqr def ghi">
        Upload file
    </div>
    <label id="select-file" for="input" class="def ghi"></label>
    <input type="file" id="input" hidden="" class="def ghi">
</div>

There is no form in the code. How to solve the problem?

Upvotes: 0

Views: 297

Answers (1)

Nikita Malyavin
Nikita Malyavin

Reputation: 2107

You need to use files parameter. Also form's action attribute can specify different upload url, so it's better to check it out.

Here's full example:

import requests
from lxml import html

host = r'https://www.example.com'
url = '/'
filename = r'C:\abc.jpg'


req = requests.get(host + url)

tree = html.fromstring(req.text)
field = tree.xpath("//input[@type='file']")
form = next(f[0].iterancestors("form"), None)
action = form.attrib['action'] if form else url

requests.post(host + action,
              files={filename: (open(filename, 'rb'), 'image/jpg')})

Upvotes: 2

Related Questions