首页 > 解决方案 > 尝试使用 selenium python 获取下拉菜单的长度时元素不存在错误

问题描述

def addtocart():
driver.get("https://www.mrporter.com/en-gb/mens/product/nike/shoes/low-top-sneakers/space-hippie-04-recycled-stretch-knit-sneakers/19971654707345242")
#driver.get("https://www.mrporter.com/en-gb/mens/product/nike/shoes/low-top-sneakers/plus-sacai-blazer-low-colour-block-leather-sneakers/10163292708776845?ntfyeu=jo5suw")

txt = driver.find_element_by_xpath("/html/body/main/div/div[2]/div/div[1]/div[2]/div[8]/div[2]").text
while "Sorry, this item is sold out" in txt:
    txt = driver.find_element_by_xpath("/html/body/main/div/div[2]/div/div[1]/div[2]/div[8]/div[2]").text
    time.sleep(2)
    driver.refresh()
    print("Item out of stock , waiting for product")
else:
    print("The product is in stock!")
    
    #Locates dropdown menu and clicks it
    dropdown = driver.find_element_by_xpath("/html/body/main/div/div[2]/div/div[1]/div[2]/div[6]/div/div/div")
    dropdown.click()

    
    select=Select(driver.find_element_by_class_name("CombinedSelect11__field CombinedSelect11__field--placeholderText CombinedSelect11__field--nativeSelect"))
    print(len(select.options))




    

添加到购物车()

我想

  1. 找到下拉菜单的选择类 2)获取下拉菜单的长度 3)选择一个介于 0 和下拉菜单长度之间的随机数 4)单击与该数字匹配的选项。

它说该元素不存在。我尝试使用完整的 x-path 和类名,但是都给了我同样的错误。

标签: pythonseleniumselenium-chromedriverwebautomation

解决方案


试试这个选择器,而不是完整的 xpath。我可以单击并打开下拉列表。

dropdown = driver.find_element_by_css_selector('div.CombinedSelect11')

也代替

select=Select(driver.find_element_by_class_name("CombinedSelect11__field CombinedSelect11__field--placeholderText CombinedSelect11__field--nativeSelect"))

尝试

select=Select(driver.find_element_by_css_selector("CombinedSelect11__field.CombinedSelect11__field--placeholderText.CombinedSelect11__field--nativeSelect"))

class_name 函数不处理类名之间的空格。


推荐阅读