Unable to upload file using python selenium webdri

2019-07-23 17:14发布

I am attempting to upload a file using selenium web driver. I get the file upload dialogue box to open in both MacOS and Windows, after which nothing happens. Wondering why selenium does not open the file via the upload dialog?

Webdriver commands I am using:

wd.get("http://www.dropzonejs.com/")
wd.find_element_by_css_selector("div.dz-message").click()
wd.find_element_by_css_selector("input.dz-hidden-input").click()
elm = wd.find_element_by_xpath("//input[@type='file']")
elm.send_keys("/Users/bg/Downloads/YOURFILE.PDF")
elm.submit()

2条回答
Rolldiameter
2楼-- · 2019-07-23 17:52

Don't click the file input element - it would trigger a file upload dialog which you cannot control via selenium. Send the keys to the input and submit the form:

elm = wd.find_element_by_xpath("//input[@type='file']")
elm.send_keys("/Users/bg/Downloads/myfile.PDF")
elm.submit()

submit() in this case is called on an input element - selenium would find the corresponding to the input element form and submit it.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-23 18:05

I finally found the code I was looking for to solve my problem. I'm going with 2 hours of research to find a solution to my problem. In my case I needed to send an image of my pc to a program through python. The page only has 1 button to upload the photo and one to send. Thank you very much for having made the code available

exemple of a program python:

from selenium import webdriver
browser=webdriver.Chrome()
browser.maximize_window()
browser.get(('http://127.0.0.1/namepage.exp'))
elm = browser.find_element_by_xpath('//*[@id="exp_file"]') #
elm.send_keys("C:\PycharmProjects\\varios\image.png")
elm.submit()
查看更多
登录 后发表回答