Error 'Unable to locate element' when tryi

2020-05-01 03:36发布

问题:

I am trying to locate Add to Cart button on Flipkart but it does not work

I have tried below xpaths but none works

By AddToCart= By.xpath("//button[@class='_2AkmmA _2Npkh4 _2MWPVK'][text()='ADD TO CART']");

OR

By AddToCart= By.xpath("//button[text()='ADD TO CART']");

//error

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='_2AkmmA _2Npkh4 _2MWPVK'][text()='ADD TO CART']"}

回答1:

Try this one.

By CSS Selector -- .row .col > button

By XPath -- .//button[text()='ADD TO CART']



回答2:

Try this xpath:

.//ul[@class='row']/li/button


回答3:

Try the following Xpath.

//button[@class='_2AkmmA _2Npkh4 _2MWPVK' and contains(.,'ADD TO CART')]

or

//button[contains(.,'ADD TO CART')]

By AddToCart= By.xpath("//button[@class='_2AkmmA _2Npkh4 _2MWPVK' and contains(.,'ADD TO CART')]");


回答4:

This error message...

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='_2AkmmA _2Npkh4 _2MWPVK'][text()='ADD TO CART']"}

...implies that the WebDriver was unable to locate the element.

You were pretty close. To locate and click() on the element with text as ADD TO CART you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ul.row>li>button"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[text()='ADD TO CART']"))).click();
    


回答5:

You try with the class also.

Something like this below.

//button[@class='_2AkmmA _2Npkh4 _2MWPVK']