tendaitakas
tendaitakas

Reputation: 358

Select an option with Python selenium

I am trying to select South Africa from the option list below:

<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>

I have tried using xpath like the solotion here :

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

but this results in:

Exception has occurred: NoSuchElementException

I have then assumed that maybe the form is been rendered after the page has finished loading and I applied WebDriverWait:

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

and it results in:

Exception has occurred: TimeoutException

If I use Chrome developer tools and search for the element using xpath it shows that the xpath is valid.

The webpage in question: https://www.mukuru.com/sa/send-money-to-nigeria/

Upvotes: 1

Views: 456

Answers (1)

frianH
frianH

Reputation: 7563

Your element target inside a frame:

<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

You need switch it first, recommendations using .frame_to_be_available_and_switch_to_it.

To select dropdown you can use Select class, with .select_by_visible_text('...') method:

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')

Upvotes: 1

Related Questions