简体   繁体   中英

Find element in Selenium using XPATH or CSS Selector

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>

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.

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

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.

By reviewing this link (Thanks to @Arran), the above issue was fixed. 'switching' to the current IFrame directs Selenium to show any requests to that frame instead.

driver.SwitchTo().Frame() 

You can do this by chaining Selenium 'FindElement' like so;

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'.

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. I find this better for more complex Selenium lookups;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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