简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM