【问题标题】:Element doesn't exist error when trying to get length of dropdown menu using selenium python尝试使用 selenium python 获取下拉菜单的长度时元素不存在错误
【发布时间】:2021-08-30 21:39:17
【问题描述】:
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 和类名,但是都给了我同样的错误。

【问题讨论】:

  • 尝试考虑人们花时间在您的(以前的)post 上进行的编辑。你没看到你的缩进不正确吗?
  • 那是 stackoverflow 的缩进。我知道上面代码的缩进是不正确的,我确实认为人们会花时间进行编辑
  • 不,它不是“stackoverflow 缩进”。看看How do I format my code blocks?

标签: python selenium selenium-chromedriver webautomation


【解决方案1】:

试试这个选择器,而不是完整的 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 函数不处理类名之间的空格。

【讨论】:

  • 我遇到的问题是,当我尝试获取“select.options”的长度时,我得到一个没有这样的元素“即使在更改它之后仍然出现错误。有没有办法获得长度/大小下拉菜单的@C.peck
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2023-03-16
  • 2019-10-02
  • 2021-03-13
相关资源
最近更新 更多