2014-03-06 69 views
0

在我的網頁中,我有一個html表格,它包含多個單選按鈕。我想選擇一個單選按鈕。到目前爲止,我能夠從表中找到值,但無法選擇。這是我的代碼:我在語法上遇到錯誤aname.click(); 錯誤是「方法,點擊()是未定義String類型」如何使用java中的Selenium web驅動程序從html表格中選擇字段

import java.io.*; 
import org.openqa.selenium.support.ui.ExpectedConditions; 
import org.openqa.selenium.support.ui.Select; 
import org.openqa.selenium.support.ui.WebDriverWait; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.ie.InternetExplorerDriver; 
import java.util.List; 
import java.util.concurrent.TimeUnit; 

     public class SendTxn1 { 

    static WebDriver d1=null; 

     public static void main(String[] args) throws IOException, InterruptedException 
     { 
     File file1=new File("C:\\Selenium\\IEDriverServer_Win32_2.35.3\\IEDriverServer.exe"); 
     System.setProperty("webdriver.ie.driver",file1.getAbsolutePath()); 

     d1= new InternetExplorerDriver(); 
     d1.get("http://10.00.00.107/"); 


      WebElement table_element = d1.findElement(By.id("tblSendMoneyPayoutAgents")); 
      List<WebElement> tbl_rows=table_element.findElements(By.xpath("id('tblSendMoneyPayoutAgents')/tbody/tr")); 

      System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tbl_rows.size()); 
      int row_num,col_num; 

      row_num=1; 
      col_num=1; 
      String aname; 

       for(WebElement trElement : tbl_rows) 
       { 
        List<WebElement> tbl_col=trElement.findElements(By.xpath("td")); 


         for(WebElement tdElement : tbl_col) 
         { 
          aname = tdElement.getText(); 

          if(aname.equals("VNM - VN Shop Herat")) 

             aname.click()l 
          break;    

          System.out.println(aname); 
          col_num++; 
         } 

         row_num++; 
       }     
     } 
    } 
+0

你能提供你的html代碼嗎? – Amith

回答

0

我認爲你需要使用executeScript選擇您的單選按鈕。此方法執行一個JavaScript字符串。把它想像成是eval,但是來自Selenium。根據您使用的是哪個版本的Selenium,您可以將您的網絡驅動器轉換爲JavascriptExecutor,然後撥打executeScript

((JavascriptExecutor) d1).executeScript("alert('replace the alert with the code to select your radio button');"); 

編輯

如果你不想使用executeScript,你需要獲得對應於您的單選按鈕WebElement,然後調用其click方法。在你的情況下,你試圖打電話點擊由getText返回的字符串,因此你的錯誤:)。所以你又缺少一個選擇表格單元格中單選按鈕的步驟。

東西沿着線(XPath查詢可能是錯誤的)

List<WebElement> radio_buttons = tdElement.findElements(By.xpath('input[type=radio]')); 

EDIT 2

在複製粘貼,能形式拼出的答案,更換

aname = tdElement.getText(); 
if(aname.equals("VNM - VN Shop Herat")) 
    aname.click(); 

if(tdElement.getText().equals("VNM - VN Shop Herat")) { 
    List<WebElement> radio_buttons = tdElement.findElements(By.xpath('input[type=radio]')); 
    for(WebElement radio : radio_buttons) { 
     //now check which radio you want to click 
    } 
} 
+0

我嘗試過,以及現在我得到的錯誤爲「類型不匹配:不能從字符串轉換爲WebElement 改名爲字符串的類型」 – Huma

+0

我不知道你改變了什麼,但你不應該用你的aname變量做任何事情,除了打印它!您需要獲取單選按鈕的WebElement,然後對其執行單擊操作。要獲得單選按鈕的WebElement,您可以通過元素ID(如果您知道單選按鈕的ID)或通過xpath查詢獲取它。 – Kiran

+0

哦,我將變量類型的表單字符串更改爲WebElement。 – Huma

相關問題