我正在学习 Selenium 进行自动化测试,并且正在尝试为网站上的基本帐户注册建立一些测试步骤。
该过程将涉及获取表单中输入字段的所有 ID,然后将这些 ID 保存到变量中并回显所有这些 ID。
目前我的 XPath 看起来像:
//*[contains(concat(' ', normalize-space(@class), ' '), ' textField')]/descendant::input
其中,Firebug 突出显示了所有输入字段。
现在我的问题是,我将如何保存这些输入字段的 ID 并在 Selenium 中回显这些 ID 以进行验证/调试?
我尝试从以下来源获得更好的想法:How to store the content/value of xpath? ,但唯一回显并保存在临时变量中的只是我给它的变量的名称。
(我们将此变量称为“AllFormInputIDs”)
我们非常感谢任何和所有的帮助,并且任何有关更有效的 XPath 标记/代码标记的提示都会很棒!谢谢:)
最佳答案
您可以按照以下流程操作:
- 查找页面中所有
input
标签元素并将其存储在列表中。 - 迭代列表,使用
getAttribute()
获取属性id
方法并将其存储在另一个 Arraylist 中,如您提到的AllFormInputIDs
。 - 现在您可以迭代“AllFormInputIDs”列表来执行您想要的任何操作。
下面是上述过程的Java 代码片段:
//Opening firefox driver instance, maximizing and assigining an implicit timeout of 20 seconds.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Navigating to the site
driver.get("http://stackoverflow.com/questions/31574046/how-to-store-and-echo-all-ids-of-present-input-fields-by-xpath-in-selenium");
//Fetching all the elements with tag 'input' and putting in a List
List<WebElement> List_Inputs = driver.findElements(By.tagName("input"));
//Creating an ArrayList object
ArrayList<String> AllFormInputIDs = new ArrayList<String>() ;
//Iterating throught the input ids in List_Inputs and fetching the 'id' attribute
//where 'id' value is not an empty string
for(WebElement inputID: List_Inputs){
if(!inputID.getAttribute("id").equals(""))
AllFormInputIDs.add(inputID.getAttribute("id"));
}
//Iterating over AllFormInputIDs where the fetched id's of all Input tags are present
//and printing them
int i=1;
for(String id: AllFormInputIDs){
System.out.println("ID "+(i++)+": "+id);
}
关于selenium - 如何在 Selenium 中通过 XPath 存储和回显当前输入字段的所有 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574046/