Python Selenium: Selecting from a list by text

Question:

I have spent the past few days trying to solve this problem. I store a string in a variable and i am trying to automate using selenium to select the item whose text()=’string stored in the variable’.

I noticed i could not select some of the items in the list even though the text was exactly the same as the string i stored in the variable. The i realized today that some of the texts have a space before the next item. For example;
instead of (Architecture)
it says (Architecture )

This is the code i was running;

fc = 'COMMUNICATION'
faculty = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="agentApplicationForm'
                                                                                '"]/div/div[9]/div['
                                                                                '1]/div/span/span/span[1]')))
print(faculty.is_displayed())
faculty.click()
sleep(5)

faculty_select = driver.find_element_by_xpath(f'//*[@id="Program1FacultyInstitute_listbox"]/li[text().StartsWith("{fc}")]')
faculty_select.click()
sleep(2)

I am now trying to use text().startsWith({fc}) but i don’t think i am using a correct syntax.

This is the error i get;

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //*[@id="Program1FacultyInstitute_listbox"]/li[text().startsWith("COMMUNICATION")] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//*[@id="Program1FacultyInstitute_listbox"]/li[text().startsWith("COMMUNICATION")]' is not a valid XPath expression.
  (Session info: chrome=88.0.4324.96)

Can someone help me please.

Thank you very much.

Asked By: director

||

Answers:

Try this to search text starting with:-

//*[@id="Program1FacultyInstitute_listbox"]/li[starts-with(text(),'fc')]

Or maybe try using contains to do substring match like below. But you will need to pass more accurate text to search in order to avoid multiple matches.

//*[@id="Program1FacultyInstitute_listbox"]/li[contains(text(),'fc')]
Answered By: Aditya

if you want to select only (one) element based on (text)

you can use

faculty.click()

faculty.send_keys("value you want to select")

notice that this method works only if you want to select only one value based on string , also it works in droplist.

Answered By: MEM
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.