I need to select an element from a drop-down menu.
For example:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
1) First I have to click on it. I do this:
inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()
2) After that I have to select the good element, lets say Mango.
I tried to do it with inputElementFruits.send_keys(...) but it did not work.
Selenium provides a convenient Select class to work with select -> option constructs:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('url')
select = Select(driver.find_element_by_id('fruits01'))
# select by visible text
select.select_by_visible_text('Banana')
# select by value
select.select_by_value('1')
See also:
What is the correct way to select an using Selenium's Python WebDriver?
Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.
Just find the element and then enumerate the options, selecting the option(s) you want.
Here is an example:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[#name='element_name']/option[text()='option_text']").click()
You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver
I hope this code will help you.
from selenium.webdriver.support.ui import Select
dropdown element with id
ddelement= Select(driver.find_element_by_id('id_of_element'))
dropdown element with xpath
ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))
dropdown element with css selector
ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))
Selecting 'Banana' from a dropdown
Using the index of dropdown
ddelement.select_by_index(1)
Using the value of dropdown
ddelement.select_by_value('1')
You can use match the text which is displayed in the drop down.
ddelement.select_by_visible_text('Banana')
firstly you need to import the Select class and then you need to create the instance of Select class.
After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list.
Here is the code
from selenium.webdriver.support.select import Select
select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
As per the HTML provided:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
To select an <option> element from a html-select menu you have to use the Select Class. Moreover, as you have to interact with the drop-down-menu you have to induce WebDriverWait for the element_to_be_clickable().
To select the <option> with text as Mango from the dropdown you can use you can use either of the following Locator Strategies:
Using ID attribute and select_by_visible_text() method:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
select.select_by_visible_text("Mango")
Using CSS-SELECTOR and select_by_value() method:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
select.select_by_value("2")
Using XPATH and select_by_index() method:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[#class='select' and #name='fruits']"))))
select.select_by_index(2)
I tried a lot many things, but my drop down was inside a table and I was not able to perform a simple select operation. Only the below solution worked. Here I am highlighting drop down elem and pressing down arrow until getting the desired value -
#identify the drop down element
elem = browser.find_element_by_name(objectVal)
for option in elem.find_elements_by_tag_name('option'):
if option.text == value:
break
else:
ARROW_DOWN = u'\ue015'
elem.send_keys(ARROW_DOWN)
You don't have to click anything.
Use find by xpath or whatever you choose and then use send keys
For your example:
HTML:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
Python:
fruit_field = browser.find_element_by_xpath("//input[#name='fruits']")
fruit_field.send_keys("Mango")
That's it.
You can use a css selector combination a well
driver.find_element_by_css_selector("#fruits01 [value='1']").click()
Change the 1 in the attribute = value css selector to the value corresponding with the desired fruit.
In this way you can select all the options in any dropdowns.
driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")
print( "The title is : " + driver.title)
inputs = Select(driver.find_element_by_css_selector('#year'))
input1 = len(inputs.options)
for items in range(input1):
inputs.select_by_index(items)
time.sleep(1)
After going through a lot of posts like this one, I managed to figure out a solution that allowed me to select an item in a dropdown. I tried .send_keys, click(), and Select in various ways with no success. Ended up sending the click() command to the dropdown 3 times before clicking on the item in the dropdown.
dropMenu = browser.find_element_by_id('cmbDeviceType')
dropMenu.click()
dropMenu.click()
dropMenu.click()
deviceType = browser.find_element_by_id('cmbDeviceType_DDD_L_LBI16T0')
deviceType.click()
Definitely not super pretty, but it works.
Hope this helps someone. This was done with Python3.7.7 on Firefox 88.0.1.
Using Following Way You can Select the dropdown value.
select=browser.find_element(by=By.XPATH,value='path to the dropdown')
select.send_keys("Put value here to select it")
It works with option value:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[#class='class_name']/option[#value='option_value']").click()
I use this for all of my clicks and selecting and it always works. For a dropdown item just make sure the xpath is the actual value you want to select.
var = WebDriverWait(driver, explicit_wait_seconds).until(
EC.element_to_be_clickable((By.XPATH, self)))
# added the click here.
ActionChains(driver).move_to_element(var).click()
perform_actions()
actions.perform()
# Reset was required to clear it. Might be patched now.
actions.reset_actions()
for device in actions.w3c_actions.devices:
device.clear_actions()
from selenium.webdriver.support.ui import Select
driver = webdriver.Ie(".\\IEDriverServer.exe")
driver.get("https://test.com")
select = Select(driver.find_element_by_xpath("""//input[#name='n_name']"""))
select.select_by_index(2)
It will work fine
Dropdown WITHOUT <select>
This works for me every time I face a dropdown without <select> tags
# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")
Import ActionChains module
from selenium.webdriver.common.action_chains import ActionChains
Use ActionChains to click on the element
drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
action = ActionChains(driver)
action.click(on_element=drp_element).perform()
The best way to use selenium.webdriver.support.ui.Select class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.
In this type of situation you can also prefer as alternate solution using execute_script() as below :-
option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")
#now use this to select option from dropdown by visible text
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);
dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')
List item
public class ListBoxMultiple {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("file:///C:/Users/Amitabh/Desktop/hotel2.html");//open the website
driver.manage().window().maximize();
WebElement hotel = driver.findElement(By.id("maarya"));//get the element
Select sel=new Select(hotel);//for handling list box
//isMultiple
if(sel.isMultiple()){
System.out.println("it is multi select list");
}
else{
System.out.println("it is single select list");
}
//select option
sel.selectByIndex(1);// you can select by index values
sel.selectByValue("p");//you can select by value
sel.selectByVisibleText("Fish");// you can also select by visible text of the options
//deselect option but this is possible only in case of multiple lists
Thread.sleep(1000);
sel.deselectByIndex(1);
sel.deselectAll();
//getOptions
List<WebElement> options = sel.getOptions();
int count=options.size();
System.out.println("Total options: "+count);
for(WebElement opt:options){ // getting text of every elements
String text=opt.getText();
System.out.println(text);
}
//select all options
for(int i=0;i<count;i++){
sel.selectByIndex(i);
Thread.sleep(1000);
}
driver.quit();
}
}
I am trying to write a Python script with Selenium to see if I can automate the registration process for a sample event I created. Here is the event page: https://www.tickettailor.com/events/testing4/621753
I am able to access the page and click on "Join the guestlist" button:
from selenium import webdriver
driver = webdriver.Chrome('path_to_chromedriver')
driver.get('https://www.tickettailor.com/events/testing4/621753')
button = driver.find_element_by_link_text('Join the guestlist')
button.click()
After this, I need to select '1' from the dropdown menu of Category1 ticket and let # of tickets in Category2 remain as 0. Afterward, I need to enter the name and email to confirm my order.
However, I am not able to find the element to select the dropdown menu at all. I have tried driver.find_element_by_id,name,xpath,class_name,css_selector, but none of them have worked. I have also tried it with the select option as in:
select = Select(driver.find_element_by_id("quantity_2335182"))(quantity_2335182 is the id of the select tag in the inspect element in Chrome) and then select.select_by_value('1'). It keeps giving errors such as:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="quantity_2335182"]"}
(Session info: chrome=96.0.4664.93)
I would prefer if I don't have to specify the specific id as in "quantity_2335182" and can select the dropdown based on a general class name, tag, or css_selector. Also, I only want to select the first of the two dropdown menus (Only editing Category1 and not Category2).
wait=WebDriverWait(driver, 60)
driver.get('https://www.tickettailor.com/events/testing4/621753')
wait.until(EC.element_to_be_clickable((By.LINK_TEXT,"Join the guestlist"))).click()
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#overlay_window")))
row1=Select(wait.until(EC.presence_of_element_located((By.XPATH,"(//select)[1]"))))
row1.select_by_index(1)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#submit"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#name"))).send_keys("a")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#email"))).send_keys("a")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#email_confirm"))).send_keys("a")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#submit"))).click()
## do captcha
key=wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".h-captcha"))).get_attribute("data-sitekey")
print(key)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#submit"))).click()
Imports:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
To automate this just click the link text, switch to the iframe overlay window , use the select import and select by index and then click the next button.
You are unable to interact with the dropdown because that popup is within Iframe. So First you have to switch to iframe and then you can interact with elements.
Here, Please see it's within iframe:
Your code steps would be :
Click on that Join the guestlist Button
Switch to Iframe. i.e driver.switch_to_frame("overlay_window")
Interact with your element or dropdown as per your requirement
Once you are done with all your operation with popup, Switch to default content i.e driver.switch_to.default_content()
I am trying to click on a checkbox using selenium python. I tried
buttons = driver.find_element_by_xpath("//*[contains(text(), 'Exact')]"); buttons.click()
I keep getting
"ElementNotVisibleException:"
<button type="button" data-ng-class="{iconCheck: event.locationExactness.isExact, inputBox:!event.locationExactness.isExact}" class="link icon locationButton inputBox" data-sfs-callout-visible="relativeExactnesses.length > 1" data-sfs-callout="sfs_-sfsLocationExactness-1-place-callout" data-sfs-callout-focus="sfs_-sfsLocationExactness-1-exact" data-ng-click="updateIsExact(relativeExactnesses.length > 1 ? true : !event.locationExactness.isExact)" data-autoname="NameAPlace_msypn_LocationExactButton"><!--
--><span class="locationLabel ng-binding">Exact</span><!--
--></button>
<<pseudo:before>></<pseudo:before>>
<!--
-->
<span class="locationLabel ng-binding">Exact</span>
<!--
-->
First of all you are locating one element, but are giving it plural name buttons. I would use singular name button.
Second thing is even in your code snippet there is two span which contain Exact. You have to change your locator so, that only one element(which you want to interact with) will be selected via selector.
For example, if you want the first Exact in your code snippet, you can use this xPath:
//button[#data-sfs-callout = 'sfs_-sfsLocationExactness-1-place-callout']/span
Note: as #RajKamal already mentioned, there can be multiple elements on the page with text Exact. You can check this in dev tools by pressing F12.
As per the HTML you have shared the element with text as Exact is a Angular element so to invoke click() on the desired element you have to induce WebDriverWait for the element to be clickable and you can use the following solution:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[#class='link icon locationButton inputBox' and #data-autoname='NameAPlace_msypn_LocationExactButton']//span[#class='locationLabel ng-binding'][contains(.,'Exact')]"))).click()
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
I can click all of the other checkboxes on the page. But when it comes to this one, it won't allow me to click on it
The HTML code for the checkbox is:
<input id="ContentPlaceHolder1_wucSignInStep2_chkTC" type="checkbox" name="ctl00$ContentPlaceHolder1$wucSignInStep2$chkTC">
My code for clicking the text box:
element = driver.find_element_by_xpath('//span[span/input[#name="checkbox checkbox-primary"]]').click()
I can provide the full code if required.
There is an id associated with your input field! You can use the id to find the element
element = driver.find_element_by_id('ContentPlaceHolder1_wucSignInStep2_chkTC').click()
That should do it.
If you are getting an element not visible error then you can try the following:
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_id("ContentPlaceHolder1_wucSignInStep2_chkTC")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
driver.execute_script("arguments[0].click();", element)
The above code will make the element visible and also, put the mouse cursor over the checkbox.
I am trying to click a particular button with Selenium in Python 3.6.but button is not working.
Inspect element ;
<span class="jsgrid-pager-page">2</span>
I tried this code;
page_button = browser.find_element_by_class_name("2").click()
what should I do?
You might use link text instead of class name as '2' is not class name for any tag in your HTML code. You can try below code
page_button = browser.find_element_by_link_text("2").click();
There is no element in your example that will be found by:
browser.find_element_by_class_name("2").click()
You are searching now for a element with the class name 2, so something like <span class="2">
You can target the span by the class jsgrid-pager-page, but there wil possibly be more the one occurrence of the class name.
An other possibility is to target the element by xpath, so like:
//span/a[text()='2']
page_button = browser.find_element(By.XPATH, "//span/a[text()='2']").click()
This way the the driver is going to search for a section containing span and an anchor and a 2.
So when you want to target the first of the third one in the row you just change the number
// First
page_button = browser.find_element(By.XPATH, "//span/a[text()='2']").click()
// Third
page_button = browser.find_element(By.XPATH, "//span/a[text()='2']").click()
I suggest you read something about locators it wil help you in the future: Locators
If by
but button is not working.
you mean that the button is not redirecting to some page or doing something, than it might be explained by the href="javascript:void(0) attribute inside your a tag. The void operator after evaluating an expression would return undefined in this case, and so the browser will stay in the same page and button click would not do anything.
Please see this SO post for more information about href="javascript:void(0)
This is apart from the fact that your locator is not correct. Please fix the locator first.
There is no class name "2" added to target link HTML. You might use link text to locate required element. If with answer provided by #Ankur Singh you get NoSuchElementException it might mean that link generated dynamically and you should wait for its appearance in DOM:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
wait(browser, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "2"))).click()