【问题标题】:Targeting DOM elements from parent to grand parent produces different result将 DOM 元素从父级定位到祖级会产生不同的结果
【发布时间】:2021-11-06 14:30:47
【问题描述】:

我正在使用 selenium 来定位 3 个按钮,如下图所示

这是每个缩略图的代码

<div class="product">
    <div class="product-image">
        <img src="./images/raspberry.jpg" alt="Raspberry - 1/4 Kg">
    </div>
    <h4 class="product-name">Raspberry - 1/4 Kg</h4>
    <p class="product-price">160</p>
    <div class="stepper-input">
        <a href="#" class="decrement">–</a>
        <input type="number" class="quantity" value="1">
        <a href="#" class="increment">+</a>
    </div>
    <div class="product-action">
        <button class="" type="button">ADD TO CART</button>
    </div>
</div>

当我尝试下面的代码时,它实现了点击 3 个按钮的目标

add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product'] button")
add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)

for i in add_cart_btn_link:
    i.click()

但是当我尝试将我的选择器更改为div[class='product-action'] button 时,只点击了第一个按钮,然后出现以下错误

Message: stale element reference: element is not attached to the page document

请问这两个定位器有什么区别以及为什么它们的工作方式不同?

【问题讨论】:

    标签: python-3.x selenium-webdriver


    【解决方案1】:

    改变你的循环:

    add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product-action'] button")
    add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)
    nbrlinks = len(add_cart_btn_link)
    for i in range(nbrlinks):
        add_cart_btn_locator = (By.CSS_SELECTOR, "div[class='product-action'] button")
        add_cart_btn_link = driver.find_elements(*add_cart_btn_locator)
        add_cart_btn_link[i].click()
    

    您每次都必须重新加载项目搜索

    【讨论】:

    • 尝试了您推荐的代码,但似乎我仍然收到element is not attached to the page document 错误消息。似乎循环找不到第二个按钮
    • 我不明白为什么...全部重新加载,网址是什么?你说似乎......你确定它不在另一个代码位置吗?你必须对其他相同类型的循环做同样的事情
    猜你喜欢
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多