使用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.