【问题标题】:Selenium cant locate element by labelSelenium 无法通过标签定位元素
【发布时间】:2018-11-08 21:51:08
【问题描述】:

我正在尝试在我的页面demo.rezi.co 的左侧找到工具提示,该提示基于属性标签显示地主。 我已经起草了下面的代码。

当我运行它时,它会说:

线程 "main" org.openqa.selenium.NoSuchElementException 中的异常:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//a[@label='LANDLORDS' ]"}

这是我目前的代码:

// Test Landlord Tooltip
String expectedToolTip = "This is a test";
WebElement landlord = Driver.findElement(By.xpath("//a[@label='LANDLORDS']"));
System.out.println(landlord.getTagName());

【问题讨论】:

    标签: selenium selenium-webdriver xpath mousehover webdriverwait


    【解决方案1】:

    标签不是链接的属性,它是一个孩子。如果您真的想通过文本LANDLORDS 选择a,则必须使用以下内容:

    "//label[contains(text(),'LANDLORDS')]/ancestor::a"
    

    【讨论】:

    • 即使在使用上述代码后,我仍然遇到与以前相同的错误。可以在 -demo.rezi.co/#!/tenant 查看 HTML。线程“main”org.openqa.selenium.NoSuchElementException 中的异常:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“label [contains(text(),'LANDLORDS')] /ancestor::a"}(会话信息:chrome=70.0.3538.77)
    • 页面上有加载器,需要等到元素出现后才能找到它
    【解决方案2】:

    我仍然不确定我是否正确理解了 用例。但是,在网页 demo.rezi.co 上,您需要 鼠标悬停 到文本为 LANDLORDS 的元素上,然后您可以提取 工具提示,然后您可以使用以下解决方案:

    • 代码块:

      import java.util.List;
      import org.openqa.selenium.By;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.WebElement;
      import org.openqa.selenium.chrome.ChromeDriver;
      import org.openqa.selenium.chrome.ChromeOptions;
      import org.openqa.selenium.interactions.Actions;
      import org.openqa.selenium.support.ui.ExpectedConditions;
      import org.openqa.selenium.support.ui.WebDriverWait;
      
      public class q53216692_MouseHover {
      
          public static void main(String[] args) {
      
              System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
              ChromeOptions options = new ChromeOptions();
              options.addArguments("start-maximized");
              options.addArguments("disable-infobars");
              WebDriver Driver = new ChromeDriver(options);
              Driver.get("https://demo.rezi.co/#!/tenant");
              WebElement myElement = new WebDriverWait(Driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[.='LANDLORDS']")));
              new Actions(Driver).moveToElement(myElement).perform();
              List<WebElement> tool_tip_items = new WebDriverWait(Driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//label[.='LANDLORDS']//following::div[1]//div[@class='layout-column']/label[1]")));
              for (WebElement tool_tip:tool_tip_items)
                  System.out.println(tool_tip.getText());
          }
      }
      
    • 控制台输出:

      UPFRONT
      ADVANTAGE
      

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多