selenium webdriver 在区域中查找元素

selenium webdriver find element in region

在自动化测试工作中,我经常遇到以下问题:我想在页面上找到一个元素,但该元素必须位于页面的特定区域。

以下面为例: 我在网站上有一个带有提前输入的搜索字段。在我的侧边栏中,我有我正在搜索的元素(我们称之为 "Selenium"),但这不是我感兴趣的元素,我想看看我的预输入搜索是否提供了预期的结果搜索 "Selenium".

<body>
   <header>
      <searchfield>
         <searchresults>
            <a .... >Selenium</a>
         <searchresults>
      </searchfield>
   </header>
   <aside>
      ...
      <a .... >Selenium</a>
      ...
   </aside>
</body>

如果我在 selenium webdriver 中搜索链接文本 "Selenium",它会找到两个条目,一个在边栏中,一个在搜索字段中。 此外,我是否无法在 linkText 上使用 WaitForVisible 命令等待搜索结果,因为 Selenium 会在侧边栏中找到该元素并得出该元素已预设的结论。

所以我的问题是: "With selenium webdriver, how do I search for an element within a specific region?"

为了解决这个问题,我发现了 Xpath 的使用。有了这个,我可以在我想搜索元素的地方创建 "areas" 。例如,我来自

html/body/div/aside/div[2]/ul/li

//div[contains(@class,'coworkerwidget')]/ul/li

现在代码更加动态,如果我们的前端人员将来编辑某些内容,则更不容易出错。

关于搜索,我现在可以设置如下代码

//div[contains(@class, 'searchfield')]//div[contains(@title, 'searchfield') and contains(., '" + searchword + "')]"

首先我们指定要在搜索字段区域中查找:

//div[contains(@class, 'searchfield')]

然后我可以为我想要查找的结果设置更多条件:

//div[contains(@class, 'title') and contains(., '" + searchword + "')]

关于这些主题的一些文献供进一步阅读。

http://www.qaautomation.net/?p=388

http://www.w3schools.com/xsl/xpath_syntax.asp

Click a button with XPath containing partial id and title in Selenium IDE

Retrieve an xpath text contains using text()