我试图从下拉列表中选择一个值:
<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']"}
答案 0 :(得分:2)
B_RATES
是option
的链接文字,但不是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