簡體   English   中英

使用硒在bigbasket的購物車中搜索和添加產品

[英]Searching and adding product in cart of bigbasket using selenium

我試圖使用 selenium 在購物車中搜索和添加產品,但未能成功

  driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb");
  List<WebElement> product = driver.findElements(By.xpath("//div[@qa=\'product\']"));
    System.out.println("prdoduct=" + product.size());
    for(int i=0;i<product.size();i++)
    {
        String name = product.get(i).getText();
        System.out.println("NAME is" + name);

        String  xp= "(//button[@qa=\'add\'])" + "["+i+ "]";
        System.out.println("xp="+xp);
        if(name.contains("Cauliflower"))
        {
            System.out.println("xp" +xp);
            driver.findElement(By.xpath(xp)).click();     
         }
     }

在這個以前的產品被選中但是當我調試它是在花椰菜上但仍然被選中了以前的產品

有時元素有可能被另一個元素重疊。 這時候,正常的硒點擊會嘗試點擊重疊的元素。 所以最好使用js click,它會點擊確切的元素,即使它是重疊的

WebElement element= driver.findElement(By.xpath(xp));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);

您的 xpath 也有可能出現問題。 由於列表從 0 開始,您可能需要在 xp 中將 i in 更改為 i+1 以獲得當前選擇添加按鈕。也請嘗試此 xpath

String  xp= "(//button[@qa=\'add\'])" + "["+(i+1)+ "]";

誘導WebDriverWait (),並等待visibilityOfAllElementsLocatedBy (),並使用以下css selectorxpath

driver.get("https://www.bigbasket.com/cl/fruits-vegetables/?nc=nb"); 
List<WebElement> product =new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div[qa='product_name']>a")));
System.out.println("prdoduct=" + product.size());
   for(int i=0;i<product.size();i++)
        {
            String name = product.get(i).getText();
            System.out.println("NAME is" + name);

            if(name.contains("Cauliflower"))
            {                
                driver.findElement(By.xpath("//div[@qa='product_name']//a[text()='" + name + "']/following::button[1]")).click();     
             }
         }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM