Selenium WebDriver中的sendKeys()

时间:2012-10-25 05:58:18

标签: java selenium selenium-webdriver

我是Selenium的新手,我正在尝试使用WebDriver上传文件。在这里,我尝试使用dom元素单击“浏览”按钮,如下所示:

selenium.type("document.forms['UploadForm'].elements['browsebutton']",file.getAbsolutePath());

但由于该方法无效,我尝试使用WebDriver元素点击浏览按钮,如下所示:如何将我的dom元素更改为xpath或css选择器,如下所示?

driver.findElement(By.cssSelector("input[type=\"file\"]")).click();

我不能把xpath写为

selenium.click("xpath="//input[@name='uplaod' and @value='browsebutton']");

因为我有多个具有相同名称和值的浏览按钮。所以我需要选择使用dom元素本身。我该怎么做?

提前感谢您的帮助。

Dominik我尝试使用下面的xpath,因为没有name属性:但是没有工作

String upload="(//input[@name='bulkUnBlockUploadForm' and @value='requestFile'])[2]";
String button="(//input[@name='bulkUnBlockUploadForm' and @value='process'])[2]";

我也试过使用id:不工作

   String upload="(//input[@id='content' and @value='requestFile'])[1]";
    String button="(//input[@id='content' and @value='process'])[1]";

问题在于我的jsp,我有2个浏览按钮,它们具有相同的id和相同的值,但形式不同。我有2个提交按钮,每个浏览按钮具有相同的id和相同的值,但形式不同。所以当我正在使用上述方法点击提交按钮

3 个答案:

答案 0 :(得分:2)

这可以上传文件,对我有用。

public static void main(String[] args) 
{
     WebDriver  driver = new FirefoxDriver();
     driver.get("http://www.freepdfconvert.com/");
     driver.findElement(By.id("UploadedFile")).sendKeys("C:\\Users\\Reputa\\Downloads\\HP1.pdf");        
     try {
            Thread.sleep(4000);
        } catch (Exception e) {}
     driver.findElement(By.name("pdfsubmit")).click();
        }

答案 1 :(得分:0)

如果你有两个具有相同属性的按钮,那么要么将它们重命名为更易于访问(例如通过给它们一个唯一的id),或者尝试将你的XPath语句改为这样的:

String uploadButton1 = "(//input[@name='upload' and @value='browsebutton'])[1]";
String uploadButton2 = "(//input[@name='upload' and @value='browsebutton'])[2]";
driver.findElement(By.xpath(uploadButton1)).click();
driver.findElement(By.xpath(uploadButton2)).click();

答案 2 :(得分:0)

嗨,当我初学者我也发现同样的问题有人告诉我你不能处理Windows控件所以使用第三方应用程序,如autoit,iam使用autoit。

    1. download autoit.
    2. no need of any jars just add Runtime,getruntime().execute('path of exe');in your code
    3.code of file upload is below

Local $hWnd=WinWait("[CLASS:#32770]","",10)
ControlFocus($hWnd,"","Edit1")
Sleep(2000)
ControlSetText($hWnd, "", "Edit1", "path of file to upload")
Sleep(2000)
ControlClick($hWnd, "","Button1");

4如果你发现查询问我,你的java应用程序仍然运行。