无法从selenium python中的下拉列表中选择值

时间:2016-10-31 07:39:15

标签: python selenium web-scraping

我试图从下拉列表中选择一个值:

<select name="ctl00$ContentPlaceHolder1$_ddl_sheet_name" id="ctl00_ContentPlaceHolder1__ddl_sheet_name">
        <option selected="selected" value="0">--Select--</option>
        <option value="tbl_E_RATES">E RATES</option>
        <option value="tbl_F_RATES">F RATES</option>
        <option value="tbl_B_RATES">B RATES</option>

    </select>

但这些命令都不起作用

driver.find_element_by_css_selector("select#ctl00$ContentPlaceHolder1$_ddl_sheet_name > option[value='B_RATES']").click()

driver.find_element_by_xpath("//select[@id='ctl00_ContentPlaceHolder1__ddl_sheet_name']/option[text()='B RATES']").click()

driver.find_element_by_css_selector("select#ctl00_ContentPlaceHolder1__ddl_sheet_name > option[value='B_RATES']").click()

错误: -

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@id='ctl00_ContentPlaceHolder1__ddl_sheet_name']/option[text()='B RATES']"}

1 个答案:

答案 0 :(得分:2)

B_RATESoption的链接文字,但不是value(值为tbl_B_RATES)。试试这个:

driver.find_element_by_xpath('//select/option[text()="B RATES"]').click()

<强>更新

页面呈现完成延迟可能导致

NoSuchElementException问题。请尝试Explicit wait等待元素出现在页面上:

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

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//select/option[text()="B RATES"]'))).click()

更新2

位于iframe内的目标下拉菜单,因此您需要先切换到它,然后处理所需的元素:

driver.switch_to_frame(driver.find_element_by_xpath('//iframe[@src="http://rate.poultrybazaar.net/show_rates.aspx"]'))
driver.find_element_by_xpath('//select/option[text()="BROILER RATES (WEST BENGAL)"]').click() # Replace text with required value
driver.switch_to_default_content() # to quit from iframe