简体   繁体   中英

Unable to upload image/file in python using selenium webdriver

I'm unable to upload and save an image.

The following is the piece of code that facilitates file upload using the UI. At first, only the upload button is visible and once an image is selected from the uploader the save button is visible.

 <td colspan="1" class="actions">
                <input type="button" class="button" name="logo" id="logo-f-upload" value="Upload Image"/>
                <input type="file" id="logo-upload" accept="image/*" name="logo-upload" style="display:none" />
                <input type="submit" value="click to save" name="submit_logo_now" class="main submit_dm logo-save-focused" style="display: none"/>
                </br>
</td>

I tried driver.find_element_by_id("logo-f-upload").send_keys(os.getcwd()+"/image_test.png")

and also

driver.find_element_by_id("logo-upload").send_keys(os.getcwd()+"/image_test.png")

but it doesn't throw any error at this stage but on the next where it says "element is not visible ..." ie. the save button. On the UI, when simulating this, the file uploader doesn't open but the file_upload button value changes to the path of the image and then breaks.

I believe this is the answer which is merely a JS hack: So the problem is that the logo-upload input has style set to display:none and due to this, selenium can't find the element. The solution that works for me is using javascript to set the style to display:block , after which using send_keys(img_path) works fine.

dr.execute_script("document.getElementById('logo-upload').setAttribute('Style','display:block')")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM