Ben
Ben

Reputation: 569

How to click language/region link using Selenium Webdriver and Python?

I'm trying to just click 'North America' and 'US', at the following URL: http://www.nike.com/language_tunnel

Here are the steps I have were working for a few weeks, but now seem to not work.

# choose country/region
driver.find_element_by_xpath("(//button[@type='button'])[2]").click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li.US a"))).click()

The first command now seems to open South America and then it stalls because it is looking for US, but there is no US link under South America. I believe I need to change the xPath, but I'm not sure what is the correct xpath (and would prefer to not use xpath at all).

Upvotes: 0

Views: 409

Answers (3)

Naman
Naman

Reputation: 32028

If you might want to change the country name tomorrow, you can use the following snippet :

countryToSearch = "North America"  // you can change this accordingly, rest should work fine
for countries in driver.find_elements_by_xpath("(//button[@type='button'])"):
    countryName = countries.text
    if countryName == countryToSearch:
        countries.click()
        break

Upvotes: 0

Andersson
Andersson

Reputation: 52685

Try to use following code:

driver.find_element_by_xpath('//button[@data-region="n-america"]').click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li  a[data-country="US"]"))).click()

Upvotes: 0

alecxe
alecxe

Reputation: 474061

As you can see, locating the element by index in this case is not quite reliable. Things like the order of elements tend to change frequently. Instead, use the data-region attribute, for instance:

driver.find_element_by_css_selector("button[data-region=n-america]").click()

Upvotes: 2

Related Questions