我在其他网站上尝试了这个确切的代码,似乎工作正常。只是在披萨小屋上,它甚至无法找到一个元素,更不用说点击它了。 Thread.sleep()没有什么区别。根据编译器,问题出在评论*之间。这是代码。
package training;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class PizzaHut {
WebDriver driver;
@Test
public void open() throws Exception {
//SET UP WEBDRIVER AND OPEN WEBSITE
System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.pizzahut.com/#/home");
Thread.sleep(1000);
//CLICK PIZZA
Thread.sleep(5000);
test("before");
//**************PROBLEM*CODE**********************
driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();
//************************************************
test("clicked pizza");
//CLOSE BROWSER
Thread.sleep(15000);
driver.close();
}
public static void test(String x) {
System.out.println(x);
}
}
答案 0 :(得分:0)
我刚刚运行下面的代码,它运行得很好。无需睡觉或等待,我也在使用Chrome。
driver.get("https://www.pizzahut.com");
driver.findElement(By.id("lg-nav-pizza")).click();
答案 1 :(得分:0)
试试这个,绝对可以帮到你。
包裹培训;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class PizzaHut {
WebDriver driver;
@Test
public void open() throws Exception {
//SET UP WEBDRIVER AND OPEN WEBSITE
// System.setProperty("webdriver.chrome.driver","/Users/1mr4n/Downloads/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.pizzahut.com/#/home");
Thread.sleep(1000);
//CLICK PIZZA
Thread.sleep(5000);
test("before");
List<WebElement> webElements=driver.findElement(By.cssSelector("div.btn-group.btn-group-lg.btn-group-justified.ph-header-navigation"))
.findElements(By.cssSelector("div.btn.btn-link.ph-ghost-padding.ng-scope"));
for (WebElement element : webElements) {
if (element.getAttribute("title").equals("PIZZA")) {
element.click();
}
}
Thread.sleep(5000);
test("clicked pizza");
//CLOSE BROWSER
Thread.sleep(15000);
driver.close();
}
public static void test(String x) {
System.out.println(x);
}
}
答案 2 :(得分:-1)
你无法点击它,因为它是一个AngularJS标签,因此需要一些时间来加载:添加一些等待如下并且它可以工作(这里我只是为了简单起见添加thread.sleep,我已经增加到15000毫秒):
//CLICK PIZZA
Thread.sleep(15000);
test("before");
//**************PROBLEM*CODE**********************
driver.findElement(By.xpath("//a[@id='lg-nav-pizza']")).click();