gpt4 book ai didi

java - 使用 Java 的 WebDriver - 单击以使用 xpath 打开链接

转载 作者:行者123 更新时间:2023-12-03 16:00:40 28 4
gpt4 key购买 nike

我想在网页上打开一个链接。该链接似乎位于位于标记内的无序列表中。网页的 URL 是 selftechy.com。选项卡是 home、about、selenium。

我尝试使用 driver.findElement(By.linkText("Selenium")); 打开链接,但页面似乎失去了它的样式。我也尝试过 xpath 方法,但它也不起作用。请向我解释为什么它不起作用以及我应该如何修改代码以使其正常工作。感谢您的帮助。

HTML代码片段:

<body class="custom">
<div id="container">
<div id="page">
<ul class="menu">
<li class="tab tab-home current"><a href="http://selftechy.com">Home</a></li>
<li class="tab tab-1"><a href="http://selftechy.com/about" title="About">About</a></li>
<li class="tab tab-2"><a href="http://selftechy.com/selenium-2" title="Selenium">Selenium</a></li>
</ul>

打开链接的webdriver代码

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.*;

import org.junit.Before;
import org.junit.After;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class selftechyTestng
{
private WebDriver driver;
private String baseUrl;

@Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://selftechy.com/";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void searchElements() throws Exception{
driver.get(baseUrl);

//use By.linkText method the page lost its styling
driver.findElement(By.linkText("Selenium"));

//use xpath method to open the link doesn't work either
List<WebElement> elements = driver.findElements(By.xpath("//div[@id=page]/*[3]")).click();
driver.findElement(By.xpath("//div[@id=page]/*[3]")).click();
}

}

最佳答案

为什么要搜索 div 然后搜索子元素 - 有什么特别的原因吗?我没有看到任何优势,当然你没有得到你真正想要点击的 a 元素。在我看来使用起来要简单得多

driver.findElement(By.xpath("//a[@title = 'Selenium']")).click();

使用你必须使用的方法

driver.findElement(By.xpath("//div[@id = 'page']/ul/li[3]/a")).click(); 

关于java - 使用 Java 的 WebDriver - 单击以使用 xpath 打开链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635693/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com