查找电子商务网站中使用Selenium的第一个特殊标记产品的定位器



场景:搜索"Socks for women";在网站上点击第一个"畅销书"贴标贴项目。

我已经尝试将项目容器作为List<WebElements>并遍历每个元素,如果存在任何"畅销书"批次。我需要让第一个找到的元素点击它。不幸的是,我被这种逻辑困住了。如果有更好的解决办法,我将不胜感激。

List<WebElement> elements = driver.findElements(By.cssSelector("div[class*='s-card-container']"));
for(WebElement e : elements) {          
// iterate
}

解决方案:

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import java.util.List;
public class FindAndClickFirstAmazonBestSeller {
@Test
public void test() throws Exception {
WebDriverManager.chromedriver().setup(); // download driver if not exist (for more details google 'how to use bonigarcia selenium')
WebDriver driver = new ChromeDriver();
driver.get("https://www.amazon.com/s?k=socks+for+women&crid=O6H6S2VU5M66&sprefix=socks+%2Caps%2C74&ref=nb_sb_ss_ts-doa-p_2_6");
List<WebElement> allBestSellers = driver.findElements(By.xpath("//span[text()='Best Seller']//ancestor::div[contains(@class,'s-card-container')]/div"));
if (allBestSellers.size() > 0) {
System.out.println("Total amount of best sellers: " + allBestSellers.size());
allBestSellers.get(0).click(); // click on first item
} else {
System.out.println("There are no best sellers found");
}

Thread.sleep(10 * 1000); // sleep 10 secs, to prevent browser closing, can be removed
driver.quit();
}
}

控制台输出:

Total amount of best sellers: 2

相关内容

  • 没有找到相关文章

最新更新