Mathlearner
Mathlearner

Reputation: 117

Select from dropdown Selenium

New to Selenium. I'm trying to get it so that I can enter a name into a search box and then click on the correct name.

I have managed to write some code to go to a website and then enter what I want and press the search button. The problem is that it then shows a list of items so I'd have to click again.

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep

index = 'AMZN'

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.marketscreener.com')
sleep(6)
text_box = driver.find_element_by_css_selector('#autocomplete')
text_box.send_keys(index)

#select.select_by_index(1)

driver.find_element_by_xpath("//*[@id='recherche_menu']/table/tbody/tr[1]/td/button/img").click()

When I enter the name and don't click It presents a dropdown list so I am trying to select the first item from the dropdown as that is usually what I will want.

I attempted this by using the commented out select.select_by_index code line. But it doesn't quite work.

I just tried also using text_box.send_keys(Keys.DOWN, Keys.RETURN) to move down into the dropdown field, but this doesn't work and just returns the same as what I currently get from clicking.

To be clear what I mean is that currently the code will return this: Current return

But I want it to go straight to the Amazon page so it will return this: Want to go to this page

Any help appreciated.

Thanks

Upvotes: 1

Views: 99

Answers (1)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

This page use many JavaScript to listen the action of the mouse and the key.If you didn't focus on the searchbox,the dropdown will be disappeared.(and you couldn't find it in the source code).

Try to use ActionChains,this works fine on my PC:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep

index = 'AMZN'

driver = webdriver.Chrome()
driver.get('https://www.marketscreener.com')
action = ActionChains(driver)

sleep(4)
text_box = driver.find_element_by_css_selector('#autocomplete')
action.move_to_element(text_box)
action.click(text_box)
action.send_keys(index)
action.perform()

sleep(1)
driver.find_element_by_xpath('//*[@id="AC_tRes"]/li[1]').click()

If the result couldn't show you,maybe you need to increase the time of sleep().

Upvotes: 3

Related Questions