Select Python 硒的选项

Select an option with Python selenium

我正尝试从下面的选项列表select南非:

<select name="from_country" id="from_country" data-role="none" class="button-negative button-negative-country-select classic" >
    <option value="ZA">South Africa</option>
    <option value="ZW" selected="selected">Zimbabwe</option>
    <option value="BW">Botswana</option>
    <option value="ZM">Zambia</option>
    <option value="MW">Malawi</option>
</select>

我试过像独奏一样使用 xpath here :

driver.find_element_by_xpath("//select[@name='from_country']/option[text()='South Africa']").click()

但这会导致:

Exception has occurred: NoSuchElementException

然后我假设表单可能在页面加载完成后呈现,我应用了 WebDriverWait:

WebDriverWait(driver,20).until(EC.element_located_to_be_selected((By.XPATH,"//select[@name='from_country']/option[text()='South Africa']"))).click()

结果是:

Exception has occurred: TimeoutException

如果我使用 Chrome 开发人员工具并使用 xpath 搜索元素,则表明 xpath 有效。

相关网页:https://www.mukuru.com/sa/send-money-to-nigeria/

框架内的元素目标:

<iframe src="https://mobile.mukuru.com/mobi/pricecheck?country_shortcode=ZA&amp;iframe=1" class="homeIframe" name="calculatorFrame" scrolling="no" marginheight="0px" marginwidth="0px" allowfullscreen="" width="340px" height="430px" frameborder="1">
    #document
        ....
        ....
        YOUR TARGET HERE

需要先切换,建议使用.frame_to_be_available_and_switch_to_it

到select下拉列表你可以使用Selectclass,用.select_by_visible_text('...')方法:

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

driver.get('https://www.mukuru.com/sa/send-money-to-nigeria/')
wait = WebDriverWait(driver, 20)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'iframe.homeIframe')))
drop_down = Select(wait.until(EC.element_to_be_clickable((By.ID, 'from_country'))))
drop_down.select_by_visible_text('South Africa')