【问题标题】:How to select a drop-down menu value wihtout an id with Selenium using Python?如何使用 Python 使用 Selenium 选择没有 id 的下拉菜单值?
【发布时间】:2020-05-09 10:32:50
【问题描述】:

我需要使用 Python 和 Selenium 从没有 id 元素的下拉菜单中选择一个元素/项目。

一段 HTML 代码:

<mbo-transaction-mode-select mode="filters.mode" class="ng-isolate-scope">
    <select class="form-control input-sm ng-pristine ng-untouched ng-valid ng-empty" ng-model="mode" ng-options="value for (key,value) in vm.modes">
        <option value="" class="" selected="selected"></option>
        <option label="LIVE" value="string:LIVE">LIVE</option>
        <option label="TEST" value="string:TEST">TEST</option>
    </select>

我在 Stackoverflow 或 Google 上找到的当前选项使用了 Select 方法,但该选项使用了我很遗憾没有的 find_element_by_id。 我尝试使用:

select = Select(browser.find_element_by_xpath("//input[@ng-model='mode']"))
select.select_by_visible_text('LIVE')

但这给出了错误:

selenium.common.exceptions.NoSuchElementException:消息:无法定位元素://input[@ng-model='mode']

我还有其他方法可以选择下拉列表及其选项之一吗?

【问题讨论】:

标签: python html selenium


【解决方案1】:

您需要修复 xpath,如下所示:

element = browser.find_element_by_xpath("//select[@ng-model='mode']")
driver.execute_script("arguments[0].scrollIntoView();", element)
select = Select(element)
select.select_by_visible_text('LIVE')

【讨论】:

  • 您可以在此处找到有关 xpath 的更多信息:guru99.com/xpath-selenium.html
  • @Evhgeniy Chiruk 现在我在使用 select 时遇到了问题,我将无法在无头/无人值守的情况下运行这个......这可以避免吗?
  • 你遇到了什么异常?
  • @Evhgeniy Chiruk,当无头运行时,它会给出:selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互:元素当前不可见,可能无法操作(或通过计划任务,它会在后台自动运行脚本,非无头,我猜会发生同样的错误)
  • 在文本选择之前添加:((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
猜你喜欢
  • 2011-12-13
  • 2016-07-28
  • 2022-07-08
  • 1970-01-01
  • 2018-02-04
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多