我是Selenium自动化测试的新手,我正在进行一些基本的自动化测试,例如在Google中搜索某些内容,然后点击搜索结果中所需的链接。
下面的代码,我已经制作出来,直到我进入测试方法。我无法从Google搜索页面中选择一个链接,但我的控制台上没有显示任何错误。所以我在这个特定的行上设置了一个线程,并且它提到它可以找到链接名称但是链接名称在html代码中使用,因为我已经检查了Google检查。
我错过了一些明显的东西吗?我对Selenium比较新,所以对任何帮助表示赞赏。此外,我已尝试镜像此用户响应中的一些代码“How to click a link by text in Selenium web driver java”,但没有运气!
由于
package com.demo.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MyFirstTestScript {
private static WebDriver driver;
public static void main (String[] args) {
SetUp();
testing();
}
// TODO Auto-generated method stub
@setup
public static void SetUp () {
driver = new FirefoxDriver();
driver.get("http://www.google.co.uk");
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
@Test
public static void testing() {
driver.findElement(By.partialLinkText("BBC - Home")).click();
}
}
答案 0 :(得分:1)
您可以使用此代码:
public class MyFirstTestScript {
private static WebDriver driver;
private static WebDriverWait wait;
public static void main (String[] args) {
SetUp();
testing();
}
@setup
public static void SetUp () {
System.setProperty("webdriver.gecko.driver", "usr/local/bin/geckodriver");
driver = new FirefoxDriver();
wait = new WebDriverWait(driver,50);
driver.manage().window().maximize();
driver.get("http://www.google.co.uk");
wait.until(ExpectedConditions.elementToBeClickable(By.name("q")));
driver.findElement(By.name("q")).sendKeys("BBC" + Keys.ENTER);
}
@Test
public static void testing(){
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.linkText("BBC - Homepage"))));
driver.findElement(By.linkText("BBC - Homepage")).click();
}
答案 1 :(得分:0)
在包含 BBC - 主页的链接上的click()
旁边的 Google主页上获取 BBC 文字的搜索结果您可以使用以下代码块:
List <WebElement> my_list = driver.findElements(By.xpath("//div[@id='rso']//div[@class='rc']/h3[@class='r']/a"));
for (WebElement item:my_list)
{
if(item.getAttribute("innerHTML").contains("BBC - Home"))
item.click();
}