【问题标题】:Python selenium select from dropdown by textPython selenium 按文本从下拉列表中选择
【发布时间】:2020-05-28 19:26:25
【问题描述】:

我有一个网络流程,我正在努力实现自动化。 HTML 如下所示:

<td class="v-formlayout-contentcell">
<div class="v-select v-widget v-has-width" id="gwt-uid-46" aria-labelledby="gwt-uid-45" style="width: 225px;">
 <select class="v-select-select" size="1" tabindex="0" style="width: 225px;">
 <option value="null"></option><option value="1">21/24 Long Term Auction Credit Study</option><option value="2">21/24 Long Term Auction</option></select></div></td>

我总是知道下拉列表中有哪些选项。

如果我知道需要选择哪个选项,有没有办法根据选项文本进行选择。在这个例子中,我想选择21/24 Long Term Auction Credit Study。

我不能使用id = "gwt-uid-46",因为我担心这很容易改变。

编辑: 我注意到在 HTML 中有另一个名为 class="v-select-select" 的类。所以,到目前为止发布的答案都没有工作,因为它找到了那个类而不是我感兴趣的那个。

【问题讨论】:

    标签: selenium xpath drop-down-menu css-selectors python-3.8


    【解决方案1】:

    从 selenium.webdriver.support.ui 导入选择

    select = Select(WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.Class_name,"v-select-select"))
    select.select_by_visible_text("21/24 Long Term Auction Credit Study")
    or 
    select.select_by_value("1")
    

    【讨论】:

    • 我收到错误:selenium.common.exceptions.NoSuchElementException:消息:找不到带有可见文本的元素:21/24 长期拍卖信用研究。第二个选项给出错误:TypeError:'int'类型的参数不可迭代
    • 我已经更新了我的答案尝试添加等待,第二个选项我忘了添加双引号
    • 在显示所有下拉选项之前检查它是否在 iframe 中或是否需要点击事件
    【解决方案2】:

    要使用Selenium 和 从 中选择文本为21/24 长期拍卖信用研究 的&lt;option&gt;,您需要为@ 诱导WebDriverWait 987654328@,您可以使用以下Locator Strategies:

    • CSS_SELECTOR:

      select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "select.v-select-select"))))
      select.select_by_visible_text("21/24 Long Term Auction Credit Study")
      
    • XPATH:

      select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@class='v-select-select']"))))
      select.select_by_visible_text("21/24 Long Term Auction Credit Study")
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.support.ui import Select
      

    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多