如何通过selenium webdriver和java

时间:2018-04-19 14:37:53

标签: java selenium selenium-webdriver webdriver dropdown

更新: 我希望能够单击HTML代码中的可用选项示例。有两个选项(id =“all_setup_home”和id =“developer-console-link”)。目前,XPath我在下拉列表中随机使用点击,它将我带到选项1页面(这就是我想要的)但它不是非常动态,因为我的XPath不针对选项1或2而是下拉列表。因此,如果我想点击第二个选项,我将无法做到。

任何比这更好的东西都会非常感激。

目前正在使用的解决方法:

getElementByXPath("Settings").click();
Thread.sleep(3000);
driver.findElement(By.xpath("//ul[contains(@class,'scrollable')]")).click(); 

尚未开始工作的初始工作:

<!-- begin snippet: js hide: false console: true babel: false -->

HTML

<div class="popupTargetContainer menu--nubbin-top uiPopupTarget uimenuList uiMenuList--right uimenuList--default visible positioned" data-aura-rendered-by="101:185;a" data-aura-class="uiPopupTarget uimenuList uimenuList--right uimenuList--default" aria-labelledby="59:185;a">
  ::before
  <div role="menu" data-aura-rendered-by="95:184;a">
    <!--render facet:96:184;a-->
    <ul class="scrollable" role="presentation" data-aura-rendered-by="97:184;a">
      <!--render facet: 816:0-->
      <!--render facet: 882:0-->
      <li class="slds-dropdown__item uiMenuItem onesetupSetupMenuItem" role="presentation" id="all_setup_home" data-aura-rendered-by="893:0" data-aura-class="uiMenuItem onesetupSetupMenuItem">....</li>
      <!--render facet:826:0-->
      <!--render facet:2004:0-->
      <li class="slds-dropdown__item uiMenuItem onesetupSetupMenuItem" role="presentation" id="developer-console-link" data-aura-rendered-by="893:0" data-aura-class="uiMenuItem onesetupSetupMenuItem">....</li>
      <!--render facet:826:0-->
      <!--render facet:2004:0-->

3 个答案:

答案 0 :(得分:1)

我有类似的问题,我没有使用selenium所以我不能为你编写代码但是在你的dropdown.click()之后;你必须等一会儿,因为此刻你不等待名单开放。

答案 1 :(得分:0)

所以,我能够点击第一个从这个元素获取XPath的选项:

driver.findElement(By.xpath("//ul[contains(@class,'scrollable')]")).click();

但是,这不是非常动态,因为我无法点击第二个选项。

答案 2 :(得分:0)

根据您的评论,您可以根据您共享的HTML打开下拉列表,从下拉列表中选择一个项目,您必须诱导 WebDriverWait 以便在{ {3}}您可以使用以下代码块:

String value = "all-setup_home";
WebElement dropdown = driver.findElement(By.xpath("//span[@class='slds-icon_container slds-icon-utility-setup slds-button__icon slds-global-header__icon']"));
dropdown.click();
List<WebElement> options = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@class='popupTargetContainer menu--nubbin-top uiPopupTarget uimenuList uiMenuList--right uimenuList--default visible positioned']/div[@role='menu']/ul[@class='scrollable']//li[@class='slds-dropdown__item uiMenuItem onesetupSetupMenuItem']")));
for (WebElement option : options)
{
    if (option.getAttribute("innerHTML").equals(value))
    {
        option.click();
        break;
    }
}