简体   繁体   中英

how to click or select on very first element(value) of input dropdown box in python using selenium webdriver

I am a beginner in python web scraping and trying to automate the site. In the website which I want to scrape there is a searching filter, where I am applying filters on input box dropdown tag.
in the drop-down box, I write the country name and all country come accordingly but I am unable to select or click the very first country that comes as a value in the dropdown box. I applied some code also but my script fails and terminated.
Below is the image for better understanding. enter image description here

I also applied some code, please check below

p_location='united states'

browser.find_by_xpath("//label[contains(.,'Geography')]").first.click()
        actions_wait_time = randint(15, 30)
        time.sleep(actions_wait_time)
        loc_input = browser.find_by_xpath("//input[@placeholder='Add locations']")
        loc_input.type(p_location)
        actions_wait_time = randint(15, 30)
        time.sleep(actions_wait_time)
        loc_input.type(Keys.TAB)
        time.sleep(3)
        loc_input.type(Keys.RETURN)

I want to select the first value from the dropdown list. Please help

It's not possible to come up with the exact code without seeing the DOM of the page, however one thing is obvious: you should not be using time.sleep function as it is a some form of a performance anti-pattern.

You should go for Explicit Wait instead like:

loc_input = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Add locations']")))
first_element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, "//xpath/for/the/first/element/in/the/dropdown")))
first_element.click()

More information: How to use Selenium to test web applications using AJAX technology

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