selenium - 如何在 Selenium 中通过 XPath 存储和回显当前输入字段的所有 ID?

标签 selenium xpath selenium-webdriver firebug selenium-ide

我正在学习 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 标记/代码标记的提示都会很棒!谢谢:)

最佳答案

您可以按照以下流程操作:

  1. 查找页面中所有input标签元素并将其存储在列表中。
  2. 迭代列表,使用 getAttribute() 获取属性 id方法并将其存储在另一个 Arraylist 中,如您提到的 AllFormInputIDs
  3. 现在您可以迭代“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/

相关文章:

eclipse - java.lang.错误: Unresolved compilation problems : WebDriver/ChromeDriver cannot be resolved to a type error while executing selenium tests

selenium-webdriver - Selenium Grid 可以配置为需要身份验证吗?

java - WebDriver 找不到 - 是 [object XrayWrapper [object Text]

java - "500 Error: Failed to establish a backside connection"- Bluemix Selenium 测试

java - 在java中创建Xpath以根据另一个属性值选择一个属性值

ruby-on-rails - nokogiri 从 xml 到数组的多个元素

c# - 获取具有特定 id 值的元素的 XPath 字符串

python - selenium.common.exceptions.WebDriverException : Message: Can not connect to the Service chromedriver. exe 打开 chrome 浏览器

python - 需要验证表内的文本(Python、Selenium)

java - 如何处理没有任何元素的浏览器通知弹出窗口?