Python Selenium:按文本从列表中选择

Python Selenium: Selecting from a list by text

过去几天我一直在努力解决这个问题。我将一个字符串存储在一个变量中,我正在尝试使用 selenium 自动处理 select 其 text()='string stored in the variable'.

的项目

我注意到我无法 select 列表中的某些项目,即使文本与我存储在变量中的字符串完全相同。我今天意识到有些文本在下一项之前有一个 space。例如; 而不是(建筑) 它说(架构)

这是我的代码 运行;

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)

我现在正在尝试使用 text().startsWith({fc}) 但我认为我使用的语法不正确。

这是我得到的错误;

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)

有人可以帮我吗

非常感谢。

试试这个搜索以以下开头的文本:-

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

或者尝试使用 contains 进行子字符串匹配,如下所示。但您需要传递更准确的文本进行搜索,以避免出现多重匹配。

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