Search code examples
pythonlistseleniumdropdown

How to click on li element of a dropdown list using Selenium in Python^


I'm trying to select the li element "US" in this dropdown list of the following website: https://proxyscrape.com/free-proxy-list

Here is the python code I have but does not work:

driver.find_element_by_xpath('/html/body/main/div/div[1]/div[3]/div/div[1]/div[2]').click()
time.sleep(4)
driver.find_element_by_css_selector("#list httpcountry countryselect [value='US']")

And here is the HTML I'm working with:

<div class="nice-select selectortypes open" tabindex="0">
  <span>
    Country: <span class="current">all</span>
  </span>
  <ul class="list httpcountry countryselect">
    <li data-value="all" class="option">all</li>
    <li data-value="US" class="option">US</li>
    <li data-value="ES" class="option">ES</li>
    <li data-value="RU" class="option">RU</li>
    <li data-value="PL" class="option">PL</li>
    <li data-value="BD" class="option">BD</li>
    <li data-value="IR" class="option">IR</li>
    <li data-value="FR" class="option">FR</li>
    <li data-value="CN" class="option">CN</li>
    <li data-value="CA" class="option">CA</li>
    <li data-value="PK" class="option">PK</li>
    <li data-value="IN" class="option">IN</li>
    <li data-value="ID" class="option">ID</li>
    <li data-value="BR" class="option">BR</li>
    <li data-value="DE" class="option">DE</li>
    <li data-value="GB" class="option">GB</li>
    <li data-value="TH" class="option">TH</li>
    <li data-value="SG" class="option">SG</li>
    <li data-value="EG" class="option">EG</li>
    <li data-value="UA" class="option">UA</li>
  </ul>
</div>

Any clue on how to select this element?


Solution

  • Solution:

    You need to wait before clicking on country dropdown list, because of top-banner appears and webdriver losts the focus, dropdown closes.

    Here is the code which i wrote and script has passed after adding two sleeps in these two places:

    driver.get('https://proxyscrape.com/free-proxy-list')
    country_list = driver.find_element_by_css_selector('.list.socks4country.countryselect').find_element_by_xpath('./..')
    sleep(2)
    country_list.click()
    sleep(1)
    country_list.find_element_by_css_selector('[data-value="US"]').click()
    us = driver.find_element_by_css_selector('[class="list socks4country countryselect"] [data-value="US"]')
    assert us.get_attribute('class') == 'option selected'