如何使用Selenium和Python从数据库中选择部分文本的下拉菜单选项。

huangapple go评论83阅读模式
英文:

Howto select an option from a dropdown menu with partial text from a database with Selenium and Python

问题

# 之前当文本匹配时,我正在使用:
service = Select(driver.find_element(By.ID, "dgDSHeader_ctl02_ddlHService"))
service.select_by_visible_text(entry['service'])
# 我认为我可能可以使用XPATH来解决这个问题...但我在如何正确写语法方面遇到了困难
英文:

I currently have a DB that is entered into a website. The website recently changed a bit and now the database no longer matches the drop downs - they have added random dates into the options that are not included in my information.

The website element looks like this:

<select name="dgDSHeader$ctl02$ddlHService" id="dgDSHeader_ctl02_ddlHService" onfocus="javascript:scrollToPosition(this,0)" onchange="javascript:return SetEandA(this,dgDSHeader_ctl02_ddlHServiceType);">
	<option value="-1">Select</option>
		<option value="774703|13">Family Service Coordination - 12/14/2022-08/07/2023</option>
		<option value="774704|16">Speech Language Pathology - 01/09/2023-08/07/2023</option>
		<option value="774706|4">Family Therapy, Counseling & Training - 12/14/2022-06/26/2023</option>
		<option value="774945|15">Developmental Instruction - 12/14/2022-08/07/2023</option>
		<option value="|3">Comprehensive Multidisciplinary Evaluation</option>
</select>

The values are not static, so I can't use selectByValue

Edited to add: The drop down menu is dynamic and changes with each search, so the index varies as well, so I can't use selectByIndex either.

Previously when the text matched I was using:

 service = Select(driver.find_element(By.ID,"dgDSHeader_ctl02_ddlHService"))
        service.select_by_visible_text(entry['service'])

The data I get from the DB looks like this:

"Speech Language Pathology" or "Occupational Therapy"

I think I can possibly do this with XPATH..but im having trouble with how to properly syntax it

答案1

得分: 1

你可以将日期之前的文本映射到下拉菜单中的索引,然后通过索引选择选项。

text = '言语病理学'
service = Select(driver.find_element(By.ID, "dgDSHeader_ctl02_ddlHService"))
values = {option.text.split('-')[0].strip(): i for i, option in enumerate(service.options)}
service.select_by_index(values[text])
英文:

You can map the text before the date to its index in the dropdown and select the option by the index

text = 'Speech Language Pathology'
service = Select(driver.find_element(By.ID, "dgDSHeader_ctl02_ddlHService"))
values = {option.text.split('-')[0].strip(): i for i, option in enumerate(service.options)}
service.select_by_index(values[text])

huangapple
  • 本文由 发表于 2023年7月23日 15:01:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76746995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定