我正试图用硒刮亚马逊。
我已经写了一个脚本,但我无法从列表中选择产品。每次使用selenium检索到的列表长度不同时,xpath是否有问题?
如有任何帮助,我们将不胜感激。
步骤:
- 获取URL(amazon.com(
- 搜索充电器
- 从列表中选择第10个产品
到目前为止,我的尝试如下:
public class AmazonSearch {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "E:\geckodriver-v0.29.0-win64\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.com");
driver.findElement(By.id("twotabsearchtextbox")).click();
driver.findElement(By.id("twotabsearchtextbox")).clear();
System.out.println("Hello world!");
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("charger");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("nav-search-bar-form")).submit();
driver.findElement(By.id("a-autoid-0-announce")).click();
System.out.println("Hello world!");
driver.findElement(By.id("s-result-sort-select_2")).click();
List<WebElement> resultsList = driver.findElements(By.xpath(".//span[@class='a-size-medium a-color-base a-text-normal']"));
int size = resultsList.size();
System.out.println("Size of list = " + size);
resultsList.get(2).click();
}
- //span[text((='Related searchs']xpath查找包含'Related searchs'span text的元素。在搜索结果中搜索(ctrl+f("相关搜索"。为了确保页面加载显示为一种方式,有许多不同的方式
- 增加查找元素和处理超时异常的等待时间-执行以下操作:
公共类AmazonSearch{
public static void main(String[] args)
{
try
{
System.setProperty("webdriver.chrome.driver", "E:\geckodriver-v0.29.0-win64\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.com");
driver.findElement(By.id("twotabsearchtextbox")).click();
driver.findElement(By.id("twotabsearchtextbox")).clear();
System.out.println("Hello world!");
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("charger");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("nav-search-bar-form")).submit();
driver.findElement(By.id("a-autoid-0-announce")).click();
System.out.println("Hello world!");
driver.findElement(By.id("s-result-sort-select_2")).click();
WebElement we = new WebDriverWait(driver, 60).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Related searches']")));
List<WebElement> resultsList = driver.findElements(By.xpath(".//span[@class='a-size-medium a-color-base a-text-normal']"));
int size = resultsList.size();
System.out.println("Size of list = " + size);
resultsList.get(2).click();
}catch(TimeoutException e)
{
System.out.println(e);
}
}
}
有时WebElement
在resultsList
中的插入是在将所有充电器项目加载到页面中之前完成的,有时确实如此。首先确保页面已加载,然后插入项目。您可以使用"Explicit Wait"。尝试以下操作:
WebElement we = new WebDriverWait(driver, 25)
.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Related searches']")));
List<WebElement> resultsList = driver.findElements(By.xpath(".//span[@class='a-size-medium a-color-base a-text-normal']"));