【问题标题】:How do I identify elements by DOM attributes in Selenium?如何通过 Selenium 中的 DOM 属性识别元素?
【发布时间】:2015-12-23 00:43:53
【问题描述】:

我正在用 Java 编写一些 Selenium 测试,以后需要通过 DOM 属性查找在 html 中不可见的元素。下面的代码尝试使用“class”属性和 DOM 属性“checked”在 google 中查找搜索栏。只有第一个对我有用,第二个因“无法定位元素”而失败。

我假设我在 xpath 上做错了,或者我没有正确理解 DOM 属性。我尝试了 DOM 中的其他几个属性,但总是得到相同的结果。我也尝试使用 cssSeletor 代替 xpath,但结果相同。

如代码所示,我使用 Chrome(使用 Windows 7)。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class SeleniumTest {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Drivers\\chromedriver.exe");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        WebDriver driver = new ChromeDriver(caps);
        driver.manage().window().maximize();
        driver.get("http://www.google.com");
        WebElement elementByClass = driver.findElement(By.xpath("//input[@class='gsfi']"));
        WebElement elementByDOM = driver.findElement(By.xpath("//input[@checked='false']"));
    }
}

编辑: 如果我使用 F12 开发工具检查谷歌搜索栏,我会找到 html:

<input spellcheck="false" dir="ltr" style="border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; background: transparent url(&quot;data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D&quot;) repeat scroll 0% 0%; position: absolute; z-index: 6; left: 0px; outline: medium none;" aria-autocomplete="both" role="combobox" aria-haspopup="false" class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Søk" value="" aria-label="Søk" type="text">

如果我检查这个元素的 DOM 属性,我可以看到属性 "checked"=true。见图片:

【问题讨论】:

  • 您要查找的 html 元素是什么?当我搜索您的第二个 xpath - //input[@checked='false'] 时,我根本找不到任何元素。可以分享一下html代码吗?
  • 您的代码看起来正确,但重要的是您的 html 代码。请问你能分享一段你尝试的html代码吗?
  • 我在问题中添加了搜索框元素的html。
  • 您发布了错误的 HTML 部分。你有一个文本输入,而不是一个复选框。
  • 如果我单击该输入的 html,我可以在 chrome 的属性下看到属性“已选中:false”。我是否错误地查看了 DOM 属性?

标签: java selenium dom xpath css-selectors


【解决方案1】:

您的方法存在一些问题。

XPath 按字面意思工作

您使用的 XPath 表达式 //input[@checked='false'] 将仅匹配 input 属性 checked 明确 设置为 "false" 的元素。它不会考虑那些未设置checkedinput 元素,因此默认值为false

属性 !== 属性

如果您想知道input 是否当前被检查,您需要检查的是它的checked 属性而不是属性。该属性仅用于为属性提供初始值。之后,操作input 不会更改属性(除非您实际上编写 代码来执行此操作)。将改变的是input 的属性。你的 XPath 会检查属性,XPath 不能用于按属性选择。

您可以使用一个伪类选择器::checked

driver.findElement(By.css("input:checked"));

您可以使用input:not(:checked) 查找未选中的。

【讨论】:

  • 感谢您澄清属性和属性之间的区别。你的解决方案解决了我的问题:)
【解决方案2】:

嗨,经过一些研究和与 selenium 的初步斗争,我了解到您可以使用 Selenium JavaScriptExecutor 类执行 javascript 来访问 Web 控件的任何 DOM 属性。所以我设计了一个通用函数,只要你输入你在浏览器上搜索的那个控件的唯一 DOM 属性,它就可以搜索页面上的任何 web 控件。由于此函数遍历 DOM 层次结构,它实际上可以跨多个浏览器工作。看看吧

` 
/// <summary>
        /// Fetch the object reference of any control on the screen
        /// Please Note : Make sure you pass unique objPropNames,objPropValues    of the control,
        /// if not then the first matched control is returned
        /// </summary>
        /// <param name="driver"></param>
        /// <param name="objPropNames"></param>
        /// <param name="objPropValues"></param>
        /// <param name="elementTagName"></param>
        /// <returns></returns>
        public static IWebElement GetWebObject(IWebDriver driver,string[] objPropNames, string[] objPropValues, string elementTagName)
        {
            IWebElement webObj = null;
            //string elementPropVlu;

            //string propName, propVlu;
            try
            {
                IList<IWebElement> lstElement = driver.FindElements(By.TagName(elementTagName));
                foreach (var item in lstElement)
                {
                    //reset the flag to true for every iteration
                    bool objectFound = true;

                    for (int i = 0; i < objPropNames.Length; i++)
                    {
                        ObjPropName = objPropNames[i];
                        ObjPropVlu = objPropValues[i];
                        //get the value of the attribute
                        //elementPropVlu = item.GetAttribute(ObjPropName.ToString());
                        var elementPropVlu = (Object)null;
                        try
                        {
                           elementPropVlu = ((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0]." + ObjPropName + "; ", item);
                        }
                        catch (InvalidOperationException ex)
                        {


                        }
                        if (elementPropVlu != null)
                        {
                            if (elementPropVlu.ToString().ToLower().Trim() != ObjPropVlu.ToString().ToLower().Trim())
                            {
                                objectFound = false;
                                break;
                            }
                        }                     

                    }
                    //if all the prop values of that object are satisfied then the match is found which 
                    //means the element we are searching for is found
                    if (objectFound)
                    {
                        webObj = item;
                        break;
                    }
                }
            }
            catch (NoSuchElementException e)
            {
                //throw;
                //log the exception
            }
            return webObj;
        }` 

用法:

GetWebObject(DriverContext.Driver, new string[] { "checked", "className" }, new string[] { "false", "gsfi" }, "INPUT")

【讨论】:

    猜你喜欢
    • 2013-12-30
    • 2020-06-20
    • 2021-11-19
    • 2018-11-01
    • 2019-01-11
    • 2019-03-25
    • 2019-05-02
    • 2019-10-18
    • 2020-10-05
    相关资源
    最近更新 更多