Pari Baker
Pari Baker

Reputation: 37

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.

Upvotes: 2

Views: 7226

Answers (1)

nescius
nescius

Reputation: 65

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")))

Upvotes: 2

Related Questions