Uploading files using ruby / Selenium

六月ゝ 毕业季﹏ 提交于 2019-12-08 08:16:27

问题


I am writing a script where I click on a button (Select Photo) which opens up a file upload (explorer) box. How am I to set my file name?

This is the code I'm using to click on the Select Photo button (ruby)

driver.find_element(:id, "fileUploadButton").click

I've seen some posts that says I do not need to click on the button but to send the path to the file/image I want to upload. So how would I upload a file on c:\temp\mypicture.jpg?

Here's my full and simple code.

driver.navigate.to "http://blah blah"  #the real site is an internal site
driver.find_element(:id, "claimGiftButtonDesktop").click
sleep 5
driver.find_element(:id, "fileUploadButton").click

After clicking the fileUploadButton, that's when the explorer window will show. If I manually click on Open or double click on it, then a loading modal shows and the image is shown on the website.

Here is an IDE recording which works. I'm just having problems translating this into ruby.

open /PromoSite
click id=claimGiftButtonDesktop
click id=fileUploadButton
type  id=fileInputElem     #Value C:\\temp\\file.jpg
click id=viewProductPreviewButton

I've also added a screen shot. I click the button and the File Upload shows up. This should be something easy, so I must not be focusing on the correct id.


回答1:


As I have no your code, assume we are testing https://encodable.com/uploaddemo/

@driver.navigate.to "https://encodable.com/uploaddemo/"
element = @driver.find_element(:css, 'input[type=file]')
element.send_keys   "/full/path/to/file.jpg"
@driver.find_element(:css, 'input[type=button]').click

So, you should send the full path to the input field and press the "submit" button




回答2:


I know this is coming a year late but I just started writing a script in Selenium/Ruby and it took me some time to figure it out so wanted to post my solution (and it was as simple as 2 lines!):

*the first line inserts the file path WITHOUT clicking on the browse button, key is to separate directories using double back slashes \\

*the second line clicks on the Save/Upload button

driver.find_element(id: "Document_upload").send_keys("C:\\Users\\me\\Desktop\\my_file.txt")
driver.find_element(id: "save").click


来源:https://stackoverflow.com/questions/30352369/uploading-files-using-ruby-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!