Selenium Python:如何从下拉列表中选择项目

时间:2018-03-04 00:03:46

标签: python selenium

我可以打开下拉菜单但是我无法点击下拉菜单上的任何选项。这是我得到的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: `Unable to locate element: {"method":"xpath","selector":"//*[@id="j_c40"]/li[3]"}`

打开下拉菜单可以正常工作:

self.driver.find_element_by_xpath("//span[@class='va-sm-m']").click()

这应该从下拉列表中按下一个选项但是给我一个错误。

self.driver.find_element_by_xpath('//*[@id="j_c40"]/li[3]').click()

我想要选择的网站的代码如下所示:

<li tabindex="0" data-size="EU M 39 / W 39" class="js-select size size-two-column ncss-brand va-sm-m d-sm-ib va-sm-t ta-sm-c " data-provide="sizes.1"><span>EU M 39 / W 39</span></li>

我在这里做错了什么?

完整代码:

self.driver.get("https://www.nike.com/de/launch/")
    ui.WebDriverWait(self.driver, 100).until(EC.visibility_of_element_located((By.ID, "cookie-settings-layout")))
    element = self.driver.find_element_by_xpath('//*[@id="cookie-settings-layout"]/div/div/div/div[3]/div[2]/div').click()
    time.sleep(5)
    self.driver.find_element_by_xpath("//span[@class='va-sm-m']").click()
    time.sleep(5)
    self.driver.find_element_by_xpath('//*[@id="j_c40"]/li[3]').click()

以下是下拉列表中的链接:

https://www.nike.com/de/launch/t/air-vapormax-utility-black-orange-peel

1 个答案:

答案 0 :(得分:0)

以下代码允许我从下拉菜单中选择EU M 39 / W 39选项。

# navigate to the website with dropdown
driver.get('https://www.nike.com/de/launch/t/air-vapormax-utility-black-orange-peel')

# select the dropdown button once it is availble
dropdown = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'j_c38')))

# click the dropdown button
dropdown.click()

# find all list elements in the dropdown. 
# target the parent of the button for the list
li = dropdown.parent.find_elements_by_tag_name('li')

# click the second element in list
li[1].click()