简体   繁体   English

如何使用 Python 在 Selenium 中选择没有 id 的下拉菜单值?

[英]How to select a drop-down menu value wihtout an id with Selenium using Python?

I need to select an element/item from a drop-down menu that doesn't have an id element using Python and Selenium.我需要使用 Python 和 Selenium 从没有 id 元素的下拉菜单中选择一个元素/项目。

The piece of HTML code:一段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>

The current option I found on Stackoverflow or Google used the Select method, but that option used find_element_by_id which I unfortunately don't have.我在 Stackoverflow 或 Google 上找到的当前选项使用了Select方法,但该选项使用了find_element_by_id ,不幸的是我没有。 I tried to use:我尝试使用:

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

But this gave the error:但这给出了错误:

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

Is there another way for me the select the dropdown and one of its options?对我来说,还有另一种方法可以选择下拉列表及其选项之一吗?

You need to fix your xpath, as here:您需要修复您的 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM