使用XPATH或CSS选择器在Selenium中查找元素 [英] Find element in Selenium using XPATH or CSS Selector

查看:256
本文介绍了使用XPATH或CSS选择器在Selenium中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#中的Selenium Webdriver查找元素"import".尝试了以下代码,但没有找到它.

I m trying to find the element "import" using Selenium Webdriver in C#. 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>

一直出现以下错误:

unable to find the element

推荐答案

XPath索引器基于1,与大多数其他语言基于0的语言相反.

XPath indexers are 1-based, as opposed to most other languages whereby they are 0-based.

这意味着您实际上是在定位第二个 li元素,而该元素没有anchor元素.

This means you are actually targetting the 2nd li element, which has no anchor element.

所以:

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

但是,这个XPath查询不是很好,而且位置太严格-因此,尽管这个在之上新固定的XPath应该可以起作用,但我还是建议您考虑一下其他事情.

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或CSS选择器在Selenium中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆