首页 > 解决方案 > 为什么 selenium 只点击第一行代码而不点击另外两行?

问题描述

我首先测试了第一行代码是否可以单击 XPath,但是当我添加第二行代码以单击 By.name() 时它不起作用,所以我尝试在 XPath 中进行更改,然后在 CSS 选择器中进行更改但它只单击第一个(行的 XPath 代码)。我已经尝试过,但似乎没有单击其他两个元素。我发现它只点击第一页上的内容,并不关心新页面上的内容,我告诉点击我想做的元素。我正在使用Selenium version 3.141.59.

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\ae65255\\Desktop\\java_gui\\chromedriver.exe");       
    WebDriver driver = new ChromeDriver();
    driver.get("https://shop.palaceskateboards.com/collections/new");
    driver.findElement(By.xpath("//*[@id=\"product-loop\"]/div[@data-alpha='S-LINE JOGGER BLACK']")).click(); //only this one work 
    driver.findElement(By.name("button")).click(); //second click dosen't work?
    driver.findElement(By.linkText("Cart")).click(); //this dosen't work too?
    }

标签: javaseleniumselenium-webdriverselenium-chromedriver

解决方案


在定位元素之前添加一些等待让页面加载

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.name("button")));
button.click();

第三个定位器By.linkText("Cart")不起作用,因为按钮没有Cart文本,它在data-textandvalue属性中。

作为旁注,您应该By.partialLinkText()在查找部分文本时使用。


推荐阅读