Selenium python,使用Select()按值选择值()来搜索字符串是否包含

2024-10-03 00:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在下拉框中使用Select()find an element。但是我想输入一个部分文本,让它搜索元素是否包含它

Python

thisValue= 1875
thisElemenet = Select(browser.find_element_by_id('id_asset'))
thisElemenet.select_by_value(str(thisValue))

我的选择脚本

<select name="asset" class="form-control" id="id_asset">
  <option value="" selected="">---------</option>

  <option value="235">UN-POA-1875 (15) | Bærbar | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD</option>

  <option value="221">UN-POA-1929 (01) | Bærbar | Lenovo L490 20Q5 Core i5 8GB 256GB SSD</option>

</select>

如果我在搜索1875,我希望它能找到第一个选项


Tags: idbyvalueelementassetfindselectun
2条回答

您可以使用select和id_asset来查找下拉列表

然后你可以使用

select#id_asset option

CSS_SELECTOR查找下拉列表中的所有选项。然后迭代下拉列表,并查找每个options (text)。对于本例,第一个选项为UN-POA-1875 (15) | Bærbar | Lenovo L590 20Q7 i5-8265U 1.6 GHz 8 GB 256 SSD,然后设置if条件,如果它包含所需的文本,则选择它

select = Select(driver.find_element(By.ID, "id_asset"))
all_options = driver.find_elements(By.CSS_SELECTOR, "select#id_asset option")
for option in all_options:
    if "1875" in option.text:
       select.select_by_value(option.get_attribute('value'))

如果在你的问题中

str(thisValue)

代表1875,您可以替换上面的行

if "1875" in option.text:

if str(thisValue) in option.text:

请尝试使用以下xpath,而不是Select

//select[@id="id_asset"]//option[contains(text(), "1875")]

请尝试以下代码:

thisValue = 1875
thisElemenet = browser.find_element_by_xpath('//select[@id="id_asset"]//option[contains(text(), "{}")]'.format(thisValue))
browser.execute_script("arguments[0].click();", thisElemenet)

相关问题 更多 >