【问题标题】:How to locate an element by using any of the selenium web driver locators如何使用任何 selenium Web 驱动程序定位器定位元素
【发布时间】:2021-09-13 11:56:46
【问题描述】:

网站网址https://staging.corporatehousingbyowner.com/

嗨, 我无法通过 Selenium Webdriver with Java 找到并单击 UL > li 中的以下按钮。 使用 Chrome 驱动程序执行自动执行。

<ul>
<li><a class="list-your-prop" href="/dashboard/properties/add/">List Your Property</a></li>
<ul/>

已经尝试了以下解决方案。

1:

WebElement element = driver.findElement(By.linkText("List Your Property"));
        element.click();

2:

WebElement element = driver.findElement(By.className("menu-text"));
String elementText = element.getText();

3:

WebElement element = driver.findElement(By.xpath("//li[contains(@class,'list-your-prop')]/ul/li/a"));
        element.click();

4:driver.findElement(By.cssSelector("body &gt; header:nth-child(1) &gt; nav:nth-child(4) &gt; div:nth-child(1) &gt; div:nth-child(2) &gt; ul:nth-child(2) &gt; li:nth-child(4) &gt; a:nth-child(1)")).click();

[网页亮点][1] [1]:https://i.stack.imgur.com/FH2LR.png

请帮助,提前致谢

【问题讨论】:

    标签: java selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    两个带有List Your Property.的网络元素

    以下 xpath 在HTMLDOM 中具有唯一条目

    //div[@id='myNavbar']/descendant::a[text()='List Your Property']
    

    代码试用 1:

    WebElement element = driver.findElement(By.xpath("//div[@id='myNavbar']/descendant::a[text()='List Your Property']")); 
    element.click();
    

    代码试用 2: 显式等待:

    WebElement element  = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='myNavbar']/descendant::a[text()='List Your Property']")));
    element.click();
    

    更新 1:

    driver.manage().window().maximize();
    //WebDriverWait wait = new WebDriverWait(driver, 30);
    //driver.manage().timeouts().implicitlyWait(300, TimeUnit.SECONDS);
    driver.get("https://staging.corporatehousingbyowner.com/");
    WebElement element  = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='myNavbar']/descendant::a[text()='List Your Property']")));
    element.click();
    

    【讨论】:

    • 感谢兄弟的及时回复。但是当 Chrome 驱动程序运行时,这段代码会被执行而没有错误。然而,当点击它时,页面仍然没有移动到它应该移动的页面。你能检查一下为什么会这样吗?
    • @Gulraiz :请参阅上面更新的 1 代码,它确实对我有用。
    【解决方案2】:

    你可以使用

    driver.findElement(By.cssSelector("nav.navbar a.list-your-prop")).click();

    最好使用等待者,因为加载元素可能需要一些时间。

    【讨论】:

    • 谢谢阿列克谢。我也会考虑这个选项。
    【解决方案3】:

    您只需要从 parent -> child 遍历即可识别唯一的 xpath,因为它仅返回 2 个具有 class 属性的元素。 这是工作代码:

    driver.get("https://staging.corporatehousingbyowner.com/")
    driver.implicitly_wait(10)
    driver.find_element_by_xpath("//ul[@class='nav navbar-nav navbar-right']//a[text()='List Your Property']").click()
    

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 2020-12-29
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多