【问题标题】:Selenium python, Using Select() select_by_value(), to search if the string containsSelenium python,使用Select() select_by_value(),搜索字符串是否包含
【发布时间】:2021-11-06 19:06:27
【问题描述】:

我正在尝试在下拉框中使用 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,我希望它找到第一个选项。

【问题讨论】:

  • 可以用其他方法解决吗?而不是使用Select
  • 不一定是我需要使用的 Select()。如果我搜索 1875,我只需要 Selenium 来选择第一个选项
  • 搜索是什么意思?同样在选择中,您正在传递 id_location,其中 id 为 id_asset
  • 修复了 id_asset 错误。我的意思是其中一个选项中的文本包含 1875。我希望能够通过传递字符串 1875 来选择该元素

标签: python selenium select


【解决方案1】:

您可以使用 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:

【讨论】:

    【解决方案2】:

    代替Select,尝试使用下面的xpath:

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

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2013-06-24
      • 1970-01-01
      • 2014-11-17
      • 2022-08-19
      • 2019-05-17
      • 2013-06-26
      • 2013-11-10
      相关资源
      最近更新 更多