如何使用 Python 使用 Selenium 选择下拉菜单值? [英] How to select a drop-down menu value with Selenium using Python?

查看:39
本文介绍了如何使用 Python 使用 Selenium 选择下拉菜单值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从下拉菜单中选择一个元素.

I need to select an element from a drop-down menu.

例如:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

1) 首先我必须点击它.我这样做:

1) First I have to click on it. I do this:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2) 之后我必须选择好的元素,比如说Mango.

2) After that I have to select the good element, lets say Mango.

我尝试用 inputElementFruits.send_keys(...) 来做,但没有奏效.

I tried to do it with inputElementFruits.send_keys(...) but it did not work.

推荐答案

除非您的点击触发了某种 ajax 调用来填充您的列表,否则您实际上不需要执行点击.

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

只需找到元素,然后枚举选项,选择您想要的选项.

Just find the element and then enumerate the options, selecting the option(s) you want.

这是一个例子:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

您可以阅读更多内容:
https://sqa.stackexchange.com/questions/1355/无法选择选项使用硒-python-webdriver

这篇关于如何使用 Python 使用 Selenium 选择下拉菜单值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆