2012-10-25 75 views
0

我是Selenium的新手,我試圖使用WebDriver上傳文件。在這裏,我嘗試使用DOM元素如下點擊瀏覽按鈕:selenium中的sendKeys()WebDriver

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元素本身來接。我該怎麼做?

在此先感謝您的幫助。但是,使用ID以及不工作

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

我想:

多米尼克我曾嘗試使用下面的XPath,因爲沒有name屬性試圖不工作

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

的問題是在我jsp,我有2個瀏覽按鈕s具有相同的id和相同的值,但不同的形式。我有2個提交按鈕,每個瀏覽按鈕具有相同的id和相同的值,但不同的形式。因此,當我使用上述方法時,它同時擊中提交按鈕

+0

如果您是Selenium的新手,請抓住機會並使用** WebDriver **。你現在使用的Selenium只是一個不死生物! –

+0

你不應該爲不同的元素使用相同的'id'。確保'id'是唯一且有意義的,那麼使用'driver.findElement(By.id())'很容易訪問元素。 – dokaspar

回答

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(); 
     } 
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(); 
+0

多米尼克根據我的測試案例我wnt點擊2瀏覽button.Not第一匹配 – cxyz

+0

好的。我相應地編輯了我的答案。希望能幫助到你。 – dokaspar

+0

我已經嘗試過,但沒有得到solution.I編輯我的問題,並在那裏添加了可靠的解決方案.u可以參考它 – cxyz

0

喜當IAM初學者我也找到了同樣的問題,有人告訴我,你不能處理窗口控件,以便使用第三方應用程序,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應用程序仍然如果你發現查詢請問我。

相關問題