【问题标题】:How to detect button that is disabled and enabled with selenium?如何检测使用硒禁用和启用的按钮?
【发布时间】:2021-07-14 05:20:57
【问题描述】:

我正在尝试为自己创建一个结帐机器人。我的代码的唯一问题是它无法检测到何时启用或禁用添加到购物车按钮。

这是我在禁用按钮时得到的输入:

<button disabled="" class="button_E6SE9 primary_1oCqK addToCartButton_1op0t addToCartButton regular_1jnnf disabled_mu48L" type="submit"><span class="content_3Dbgg" tabindex="-1"><div class="addToCartLabel_YZaVX"><span>Add to Cart</span></div></span></button>

这是我在启用按钮时得到的输入:

<button class="button_E6SE9 primary_1oCqK addToCartButton_1op0t addToCartButton regular_1jnnf" type="submit"><span class="content_3Dbgg" tabindex="-1"><div class="addToCartLabel_YZaVX"><span>Add to Cart</span></div></span></button>

这就是我要让它检测按钮的方法,但是它仅在启用按钮时才有效。

while not buyButton:
    try:
        addToCartBtn = addButton = browser.find_element_by_class_name("addToCartButton")
        addToCartBtn.click()
        print("Item in stock")
    except:
        addToCartBtn = addButton = browser.find_element_by_class_name("disabled_mu48L")
        browser.refresh()
        print("Item out of stock")
        continue

我尝试过使用 XPATH 并使用不同的类名来查看它是否可以工作,但似乎没有任何效果。任何建议或提示都会有所帮助,谢谢!

【问题讨论】:

    标签: python html selenium bots


    【解决方案1】:

    使用此选择器定义add_to_cart_button 按钮button.addToCartButton

    你可以用.get_attribute('class')检查属性值:

    add_to_cart_button = browser.find_element_by_css_selector('button.addToCartButton')
    
    if "disabled" in add_to_cart_button.get_attribute('class'):
        browser.refresh()
        print("Item out of stock")
        continue
    else:
        add_to_cart_button.click()
        print("Item in stock")
    

    【讨论】:

    • 这非常有效!非常感谢:DD
    • @JenniferTsang 很高兴它起作用了,随时点击 图标接受答案,它会变成绿色。所以这个话题没有得到答复。
    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    相关资源
    最近更新 更多