简体   繁体   English

使用XPATH或CSS Selector在Selenium中查找元素

[英]Find element in Selenium using XPATH or CSS Selector

I m trying to find the element "import" using Selenium Webdriver in C#. 我试图在C#中使用Selenium Webdriver找到元素“import”。 Have tried the following codes but nothing find it. 尝试过以下代码但没有找到它。

driver.FindElement(By.XPath("//*[@class='menu_bg']/ul/li[3]")).Click();
driver.FindElement(By.XPath("//*[@id='import']/a")).Click();
driver.FindElement(By.CssSelector("#import>a")).Click();
driver.FindElement(By.XPath("//*[@class='menu_bg']/ul/li[3]/a")).Click();
driver.FindElement(By.CssSelector("ul[@class='menu_bg']>li[value='3']")).Click();

Please help me out. 请帮帮我。 Design page looks like below: 设计页面如下所示:

<body>
    <div class="header_bg"></div>
    <div class="menu_bg">
        <ul class="menu">
            <li id="retrieve"></li>
            <li id="scan" class="test"></li>
            <li id="import">
                <a target="main" href="import/import.aspx" onclick="clickme(this,'import')">Import</a>
            </li>
            <li id="admin"></li>
            <li id="help"></li>
            <li style="float: right;"></li>
        </ul>
    </div> 
</body>

All the time I got the error as below: 我一直得到如下错误:

unable to find the element

XPath indexers are 1-based, as opposed to most other languages whereby they are 0-based. XPath索引器是基于1的,而不是大多数其他语言,它们是从0开始的。

This means you are actually targetting the 2nd li element, which has no anchor element. 这意味着您实际上是在定位第二个 li元素,它没有anchor元素。

So: 所以:

//*[@class='menu_bg']/ul/li[3]/a

However, this XPath query is not great and is too strict on position - thus although this newly fixed XPath above should work, I'd advise you to think of something else. 但是,这个XPath查询不是很好,并且位置太严格 - 因此虽然上面这个新修复的XPath 应该可以工作,但我建议你想一些其他的东西。

By reviewing this link (Thanks to @Arran), the above issue was fixed. 通过查看此链接 (感谢@Arran),上述问题已得到修复。 'switching' to the current IFrame directs Selenium to show any requests to that frame instead. “切换”到当前IFrame会指示Selenium显示对该帧的任何请求。

driver.SwitchTo().Frame() 

You can do this by chaining Selenium 'FindElement' like so; 你可以通过链接Selenium的'FindElement'来做到这一点;

driver.FindElement(By.Id("import")).FindElement(By.TagName("a")); which will give you the child of the element with ID that has a tag of 'a'. 这将为您提供具有标记为“a”的ID的元素的子元素。

Another way you could do this is by casting your Driver to an IJavascriptExecutor and executing javascript directly in the browser using a JQuery selector. 另一种方法是将Driver转换为IJavascriptExecutor并使用JQuery选择器直接在浏览器中执行javascript。 I find this better for more complex Selenium lookups; 我发现这对于更复杂的Selenium查找更好;

((IJavascriptExecutor)Driver).ExecuteScript("$("a[target='main'][href='import/import.aspx'])").click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM