Reputation: 283
[Environment]: Python + Selenium
I am trying to upload a local file to the upload file button.
First of all, I tried to see if I can locate that element and click on that button and I succeed by using
driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').click()
So, I used the same way but replace the click()
with send_keys()
for file uploading.
driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin")
But it can not pass the value in.
So, I tried to use other locator as following: (None of them can work)
driver.find_element(By.XPATH, "//button[text()='Update from File']")
driver.find_elements(By.XPATH, "//*[@id='id_file']")
driver.find_elements(By.XPATH, "//input[@id='file']")
In addition, I also googled it with so many similar questions but unable to find a solution/answer.
Would like to seek your advice and shed me some light on this? Thank you.
HTML codesnippet:
<iframe id="upload_frame" height="30px" frameborder="0" width="0" src="/web/setting/upload.html?r=1422498136526" scrolling="no"
name="upload_frame" style="width: 170px;">
<!DOCTYPE html>
<html>
<head>
<body onload="page_load();">
<div id="content" class="b1">
<form id="form_firm" action="/cgi-bin/system_mgr.cgi" enctype="multipart/form-data" method="post" name="form_firm">
<input type="hidden" value="cgi_firmware_upload" name="cmd">
<div class="file_input_div">
<button id="id_file" type="button" style="border: 2px solid rgb(70, 70, 70); background: none repeat scroll 0% 0% rgb(33, 33, 33);">
<span class="_text" lang="_firmware" datafld="update_b">Update from File</span>
</button>
<input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer"
name="file">
</div>
</form>
</div>
</body>
</html>
</iframe>
Upvotes: 3
Views: 2145
Reputation: 4424
driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin")
won't work as it corresponds to the button element
not the input element
with type file.
For simple file upload using selenium, you must first search for the input tag with type as file. As in your code, that must be:
<input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer" name="file">
Please use the below code for the file-upload to work:
driver.switch_to_frame("upload_frame")
driver.find_element(By.ID, 'file').send_keys('//path of the file to upload')
Note:- The above corresponds to the "input tag with type file".
Upvotes: 2