使用python selenium(xpath)下拉列表选择

时间:2017-05-31 04:46:13

标签: python-2.7 xpath selenium-webdriver drop-down-menu

   Month 
<select name="filterMonth" onchange="document.form.submit()">
<option value="0"></option>
  <option value="01">January</option>
  <option value="02">February</option>
  <option value="03">March</option>
  <option value="04">April</option>
  <option value="05">May</option>
  <option value="06">June</option>
  <option value="07">July</option>
  <option value="08">August</option>
  <option value="09">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select>

如何使用xpath选择"filterMonth"的下拉列表?

browser.find_element_by_xpath('//*[@id="form"]/table[1]/tbody/tr[3]/td[2]/select[2]') 

给我错误,找不到这样的元素

3 个答案:

答案 0 :(得分:0)

您可以使用xpath

//select[@name='filterMonth'] 

如果名称在整个页面中是唯一的。

Select select =new Select(driver.findelement(By.xpath("//select[@name='filterMonth']")));
select.selectByVisibleText("January");

这适用于Java。请相应更改python。

答案 1 :(得分:0)

获得NoSuchElementException的原因之一可能是tbody中使用XPath标记,因为此标记并非始终存在于初始HTML来源中,但可能会生成动态。另一个原因是整个table可以动态生成,你应该稍等一下才能处理它:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

select = wait(browser, 10).until(EC.presence_of_element_located((By.NAME, "filterMonth")))
Select(select).select_by_visible_text("March")

您也可以使用@Murthi //select[@name="filterMonth"] XPath提供的选择下拉列表

答案 2 :(得分:0)

您可以尝试以下代码:

select = Select(driver.find_element_by_xpath("//select[@name='filterMonth']"))

# select by visible text
select.select_by_visible_text('January')