【问题标题】:msg no such element: Unable to locate element:味精没有这样的元素:无法找到元素:
【发布时间】:2020-07-28 16:55:49
【问题描述】:

HTML:

“加入购物车”对象

<button class="button spin-button prod-ProductCTA--primary button--primary" data-automation-id="button" data-tl-id="ProductPrimaryCTA-cta_add_to_cart_button" type="button"><span class="button-wrapper"><span class="spin-button-children">Add to cart</span></span></button>

“进货提醒”对象

<button class="button spin-button prod-ProductCTA--primary button--primary" data-automation-id="button" data-tl-id="cta_oos_button" aria-expanded="false" aria-label="get in stock alert" role="button" tabindex="0" type="button"><span class="button-wrapper"><span class="spin-button-children">Get in-stock alert</span></span></button>

我不想点击“加入购物车”。我只想将定位器信息存储在 WebElement“addToCart”中。因为对象具有非常相同的属性,所以我选择了这个独特的属性“data-tl-id”但是没有用。

网络驱动程序

WebElement addToCart = driver.findElement(By.xpath("//button[@data-tl-id='ProductPrimaryCTA-cta_add_to_cart_button']"));

下面对我有用,但上面两个对象都有相同的类名,所以我不能使用类名。

WebElement addToCart  = driver.findElement(By.xpath("//span[@class='button-wrapper']"));

我也尝试了以下方法,但没有一个对我有用。

WebElement addToCart = driver.findElement(By.xpath("//span[text()='Add to cart'"));

WebElement addToCart = driver.findElement(By.xpath("//span[contains(@text,'Add to cart')]"));

我收到错误“没有这样的元素:无法找到元素:”。如何定位“加入购物车”对象?

【问题讨论】:

    标签: selenium


    【解决方案1】:

    您的xpath 错误WebElement addToCart = driver.findElement(By.xpath("//span[text()='Add to cart'"));

    试试下面的解决方案

    WebDriverWait wait = new WebDriverWait(driver, 30);
    WebElement webElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Add to cart']")));
    System.out.println("Printing "+webElement.getText());
    

    或者你也可以用contains试试xpath

    WebDriverWait wait = new WebDriverWait(driver, 30);
    WebElement webElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(),'Add to cart')]")));
    System.out.println("Printing "+webElement.getText());
        
    

    【讨论】:

    • 两个等待语句都只是试图等待对象。如何将其存储到 WebElement“addToCart”中?
    • 检查更新的解决方案,您可以对 webElement 执行操作。
    • @GreenTree :如果您的问题得到解决,那么您是否愿意接受回答。
    • 完成。谢谢!
    【解决方案2】:

    因为这个xpath 为你工作,

    WebElement addToCart  = driver.findElement(By.xpath("//span[@class='button-wrapper']"));
    

    使用它来唯一标识 WebElement

    driver.findElement(By.xpath("//button[contains(@data-tl-id,'cart')]/span[@class='button-wrapper']"))
    

    你也可以使用这个xpath

    //span[contains(text(),'Add to cart')]
    

    【讨论】:

    • 这个是里面的span标签-&lt;span class="spin-button-children"&gt;Add to cart&lt;/span&gt;。您认为您的xpath 正确吗?
    • 他正在用@class 'button-wrapper' 识别span
    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2020-07-24
    • 2017-12-08
    相关资源
    最近更新 更多