我想在网页上打开一个链接。该链接似乎在一个无序列表中,该列表驻留在一个标签中。该网页的url是selftechy.com。标签是主页,关于,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();
}
}发布于 2013-05-19 23:34:16
为什么要先搜索div,然后再搜索子元素--有什么特殊的原因吗?我看不出有什么好处,而且你肯定得不到你真正想要点击的a元素。在我看来,使用它要简单得多。
driver.findElement(By.xpath("//a[@title = 'Selenium']")).click();使用你的方法,你必须使用
driver.findElement(By.xpath("//div[@id = 'page']/ul/li[3]/a")).click(); 发布于 2013-05-21 03:05:29
您还可以使用以下xpath:
"//a[text()='Selenium']"这将找到包含text = Selenium的链接
发布于 2013-10-16 20:40:26
下面的代码将在新窗口中打开链接,并打印新打开窗口的标题和url。
String defaultwindow = "";
@Test(description="Main Page")
public void UserOnMainPage()
{
driver.get("http://yoururl.com");
defaultwindow = driver.getWindowHandle();
String selectAll = Keys.chord(Keys.SHIFT,Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);
printTitleandUrlofNewlyOpenedwindow();
}
private void printTitleandUrlofNewlyOpenedwindow()
{
Set<String> windowHandles1 = driver.getWindowHandles();
int size = windowHandles1.size();
System.out.println(size);
for (String string : windowHandles1)
{
driver.switchTo().window(string);
if(string.equals(defaultwindow))
{
System.out.println("On Main Window");
Reporter.log("On Main Window");
}
else
{
String title=driver.getTitle();
System.out.println(title);
Reporter.log(title);
String recipeUrl = driver.getCurrentUrl();
System.out.println(recipeUrl);
Reporter.log(recipeUrl);
}
}
driver.switchTo().window(defaultwindow);
}https://stackoverflow.com/questions/16635693
复制相似问题