how to select by a partial text in Python - selenium - python

How can I select a dropdown element by a part of its name?
I want to select an option based on a DB values, but this values don't have the complete name of the dropdown element, is there any way to make selenium look for the option with my database value as a partial text?
modelo = googleSheet.modelo.upper().strip()
select = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div/div/div[1]/form/fieldset[6]/div/ul/fieldset[3]/div/ul/fieldset[3]/div/ul/fieldset/div/ul/li/label'))))
select.select_by_visible_text(modelo)
I the dropdown option I want to select is "Terrano II 2.7 xpto ol", but my data base value is just Terrano II 2.7
Thanks for the help

driver.select_by_visible_text() already does strip(). You do not need it.
Also, from this method definition:
Select all options that display text matching the argument. That is, when given "Bar" this would select an option like:
<option value="foo">Bar</option>
:Args:
- text - The visible text to match against
So, you need to expect exactly the option that is visible.
Another problem in your code is the way you pass the variable.
dropdown_option = "Some text you expect to see in the dropdown"
locator = driver.find_element_by_id("id") # or any other locator
select = Select(locator)
if locator is not None:
for option in select.options:
select.select_by_visible_text(dropdown_option)
This implementation makes debugging easier. For example you can print all the values from your dropdown before selecting the option you need.
If it takes a lot of time to dropdown to open, or other elements make your dropdown temporarily not visible, add a separate wait before selection.
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, "Unique css selector of the first option in dropdown")))

What about if first you extract the dropdown text content and then you check if your db query is in text? something like this:
Selenium Select - Selecting dropdown option by part of the text

Related

How to select a value from drop down menu in python selenium

I am writing a python script which will call a webpage and will select an option from the drop down to download that file. To do this task, I am using chropath. It is a browser extension which can give you the relative xpath or id for any button or field on the webpage and using that we can call it from python selenium script.
Above image shows the drop down menu in which I have to select 2019 as year and the download the file. In the lower part of the image, you can see that I have used chropath to get the relative xpath of the drop down menu which is //select[#id='rain']
Below is the code I am using:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("<URL>")
driver.maximize_window()
grbf = driver.find_element_by_xpath("//select[#id='rain']")
grbf.send_keys('2019')
grbf_btn = (By.XPATH, "//form[1]//input[1]")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable(grbf_btn)).click()
from the above code, you can see that I am using xpath to select the drop down grbf = driver.find_element_by_xpath("//select[#id='rain']") and then sending keys as 2019 i.e. grbf.send_keys('2019') and after that I am calling download button to download it. But for some reason, its always selecting year 1999 from the drop down. I am not able to understand what is wrong in this. Is this correct approach to solve this. Please help. Thanks
I had the same problem time ago. Try this:
from selenium.webdriver.support.ui import Select
grbf = Select(driver.find_element_by_xpath("//select[#id='rain']"))
grbf.select_by_value('2019')
In the select_by_value() you have to use the value of the element in the dropdown.
By the way, if an element has id, use it.
grbf = Select(driver.find_element_by_id('rain'))
Try below code:
select = Select(driver.find_element_by_xpath("//select[#id='rain']"))
select.select_by_visible_text('2019')
Another approches to deal with dropdown:
Using Index of Dropdown :
select.select_by_index(Paass index)
Using valueof Dropdown :
select.select_by_value('value of element')
Using visible text of Dropdown :
select.select_by_visible_text('element_text')
In my opinion, I don't think this is the correct approach. You try to select the option which is dropdown (not a text box like ), so send key command does not work.
What you need to do is try to inspect HTML changing when clicking the dropdown and try to XPath for an option that you want to select.
If you still stuck at this problem, I recommend using katalon recorder which is a chrome extension to allow you to record and do UI testing

how to get unique XPATH for buttons when the features for all input are the same

I am trying to extract NBA players stats using selenium web driver in python and here is my attempt:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
browser = webdriver.Chrome()
browser.get('https://www.basketball-reference.com')
xp_1 = "//select[#id='selector_0' and #name='team_val']"
team = Select(browser.find_element_by_xpath(xp_1))
team.select_by_visible_text('Golden State Warriors')
xp_2 = "//select[#id='selector_0' and #name='1']"
player = Select(browser.find_element_by_xpath(xp_2))
player.select_by_visible_text('Jordan Bell')
The problem I have is there are 4 "Go" buttons in this page and all have the same input features. In other words, the following xpath returns 4 buttons:
//input[#type='submit'and #name="go_button" and #id="go_button" and #value="Go!"]
I unsuccessfully tried adding ancestor as below but it does not return an xpath:
//input[#type='submit' and #name="go_button" and #id="go_button" and #value="Go!"]/ancestor::/form[#id='player_roster']
I appreciate any insight!
Try below XPAth to select required Go button:
"//input[#value='Go!' and ancestor::form[#id='player_roster']]"
or
"//form[#id='player_roster']//input[#value='Go!']"
Note that you shouldn't mix single and double quotes in a XPath expression and correct usage of ancestor axis is
//descendant_node/ancestor::ancestor_node
You could also switch to CSS selectors and use a descendant combination where you use an parent element to restrict to the appropriate form with Go button
#player_roster #go_button
That is
browser.find_element_by_css_selector("#player_roster #go_button")
The # is an id selector.
CSS selectors are generally faster than XPath, except in cases of older IE versions. More info.

Selecting an item from drop down menu when the menu uses input, not select

I'm trying to learn how to use Selenium with Python. I'm writing some code that will run a search on www.kijiji.ca. I'm able to select the search field and enter my query, but I can't figure out how to select the city from the list. In the Selenium documentation, I found where it says to use:
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_name('name'))
However, when I try to use the code, I get an error that says "Select only works on select elements, not on input"
I inspected the page again and it does seem like the drop down menu uses an input rather than a select. Can anyone help me figure out how to use Selenium to select the city here?
You can use Select class if your element is a <select> tag. Refer seleniumhq, there it mentionedModels a SELECT tag, providing helper methods to select and deselect options.
Specific to you element, you can try below code as manually we simulate the action like click.
driver.find_element_by_id("SearchLocationPicker").click()
driver.find_element_by_css_selector("li a[title='Manitoba']").click()
driver.find_element_by_css_selector("li a[title='Flin Flon']").click()
Working fine at my end. let me know if you have any query.
The page uses custom select component which cannot be interacted with selenium Select class. The Select class can be used only for default html select component.
We have to automate it as we do in the manual steps,
Click the input test box
Wait for the dropdown list appears.
Click the value respective value appears in the the dropdown.
In your case, we can select the dropdown either with title attribute or by selecting display value of the anchor tag in the list.
<a title="Territories">Territories</a>
def select_by_title(value):
# click the input component
driver.find_element_by_css_selector('input#SearchLocationPicker"]').send_keys(value)
# Wait for the value to appear in dropdown.
wait = WebDriverWait(driver, 60)
element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#SearchLocationPicker~div>ul>li>a[title="'+value+'"')))
# Click the element
element.click()
Or
def select_by_display_value(value):
driver.find_element_by_css_selector('#SearchLocationPicker"]').send_keys(value)
wait = WebDriverWait(driver, 60)
element = wait.until(EC.visibility_of_element_located((By.XPATH, '//input[#id="SearchLocationPicker"]/following-sibling::div/ul/li/a[text() = "'+value+'"]')))
element.click()

selenium select by visible text in python

Hi I am trying to use selenium to select an item from a dropdown using the actual text not the value option. My script pulls states out of a list and iterates through the states selecting the dropdown that matches the list.
When I try the following code it throws out an error:
for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
select2 = driver.find_element_by_css_selector("#selst" %agentstate1)
select2.click()
select2 = driver.find_element_by_css_selector("#selst" %agentstate1)
TypeError: not all arguments converted during string formatting
I'm wondering if the error is thrown out becuase when I grab the data that I put in my list I append a "\n" but even when I take out that code it does not work.
you are using css IDs instead of CSS classes. select2 is pointer to the select element, if your text is exactly the same as in your variable
from selenium.webdriver.support.ui import Select
for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
select2 = Select(self.driver.find_element_by_id("<some id of the select element>")).select_by_visible_text(agentstate)
if it is only partial match you can try this (case insensitive partial match):
from selenium.webdriver.support.ui import Select
for agentinfo1, agentstate1 in zip(agentinfo, agentstate):
select2 = Select(self.driver.find_element_by_id("<some id of the select element>"))
for each_option in select2.options:
if agentstate.lower in each_option.text.lower:
select2.select_by_index(int(each_option.get_attribute("value")))

Selenium Hidden Elements: Hidden <option> Elements Within <select>

I am trying to select a particular option within a select box on a webpage. http://www.arnoldporter.com/news.cfm.
Specifically I want to selection "FDA and Healthcare" option within the Practice/Industry selection box.
I have tried a number of things, including clicking on the select tag, and then clicking on the FDA option. I have also checked to see whether the select tag changes after being clicked on. It doesn't.
So, Nothing seems to work, I keep getting the same error: Element is not currently visible and so may not be interacted with.
The xpath I am using for the select box is: //select[#class="medium" and #name="search_practice_id"]
The xpath I am using for the option is: //option[#value="323"]
There must be a simple solution, I just can't figure it out. Any help would be appreciated.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
URL = 'http://www.arnoldporter.com/news.cfm'
CSS_SELECTOR = 'select[name=search_practice_id][class=medium]'
OPTION_TEXT = 'FDA and Healthcare'
browser = webdriver.Chrome()
browser.get(URL)
select_el = browser.find_element_by_css_selector(CSS_SELECTOR)
select = Select(select_el)
select.select_by_visible_text(OPTION_TEXT)

Categories