1
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Testing\\Downloads\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://jpetstore.cfapps.io/login");
    driver.manage().window().maximize();
    driver.findElement(By.name("username")).sendKeys("Testing");
    driver.findElement(By.name("password")).sendKeys("test@123");
    driver.findElement(By.id("login")).click();
    driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]/img")).click();

在这里,我能够创建动态 xpath driver.findElement(By.xpath("//div[@id='Catalog']//parent::td//preceding-sibling::td//a//following:: td//a")).click(); driver.findElement(By.xpath("//div[@id='Catalog']//parent::a//following::a[contains(text(),'Add to Cart')]")).点击(); driver.findElement(By.xpath("//div[@id='BackLink']//a[contains(text(),'返回主菜单')]")).click(); driver.findElement(By.xpath("//div[@id='SidebarContent']//a[@href='/catalog/categories/FISH']")).click();

4

1 回答 1

0

如果要单击该链接,则需要使用 xpath 直到a节点,请尝试以下 xpath :

String xPath = "//div[@id='SidebarContent']/a[contains(@href,'FISH')]";

如果您仍然遇到异常,那么您需要在单击它之前延迟一些时间:

 Thread.sleep(3000);
 driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]")).click();

您可以使用 FluentWait 来避免一些异常,如果您想使用 FluentWait,请尝试以下代码:

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
WebElement fish = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
    return driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]"));
    }
});
fish.click();

更新 :

根据评论中的讨论,这是解决方案:

driver.get("https://jpetstore.cfapps.io/login");
driver.manage().window().maximize();
driver.findElement(By.name("username")).sendKeys("some username");
driver.findElement(By.name("password")).sendKeys("some password");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[@id='SidebarContent']/a[contains(@href,'FISH')]")).click();
// Replace Name('Angelfish') with any fish you want
driver.findElement(By.xpath("//td[text()='Angelfish']/preceding-sibling::td/a")).click();

// Replace Description('Small') with any size you want
driver.findElement(By.xpath("(//span[text()='Small']/parent::td/following::td//a[@class='Button'])[1]")).click();

我希望它有帮助...

于 2019-02-13T03:39:57.250 回答