python - 如何通过 selenium 和 python 从下拉菜单中选择元素?

标签 python python-3.x selenium selenium-webdriver selenium-chromedriver

我正在尝试通过 selenium 驱动程序和 python 进行自动登录测试。 我正在使用这个网站 https://invoiceaccess.pgiconnect.com/ 我做了什么:


    from selenium import webdriver
    driver = webdriver.Chrome()

    driver.get("https://invoiceaccess.pgiconnect.com")
    driver.find_element_by_id("LoginId").send_keys("test-account")
    driver.find_element_by_id("LoginPassword").send_keys("test-password")
    #driver.find_element_by_id("submit").click()

一切正常,但我在从下拉菜单中进行选择时遇到问题。例如,我有这个菜单的 html 代码。

    <select class="regiondropdown" data-val="true" data-val-required="Please Select Region" id="Region" name="Region"><option value="">Select Region</option>
    <option value="us">America</option>
    <option value="europe">Europe</option>
    <option value="apac">APAC</option>
    </select>

我试过这个:

    element = driver.find_element_by_xpath("//select[@name='Region']")
    all_options = element.find_elements_by_tag_name("option")
    for option in all_options:
        print("Value is: %s" % option.get_attribute("US"))
        option.click()

例如,我需要选择America,但它选择了APAC。我哪里出错了,谁能帮帮我?

最佳答案

要检索具有 us 值的 select 元素的特定选项,您可以使用 Select Selenium 类做这样的事情:

from selenium.webdriver.support.ui import Select

option = Select(
    driver.find_element_by_xpath("//select[@name='Region']")
).select_by_value("us")
print(option.text) # Should print 'America'

或者你也可以用 css 选择器做到这一点:

selec = driver.find_element_by_xpath("//select[@name='Region']")
option = selec.find_element_by_css_selector("option[value=\"us\"]")
print(option.text) # Should print 'America'

关于python - 如何通过 selenium 和 python 从下拉菜单中选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54100588/

相关文章:

python - 其他线程中的 QMessageBox

python - 如何从python安装文件中排除特定的依赖包版本

java - 找不到按钮元素 SELENIUM

python3.3在linux中找不到libpython3.3m.so(pip-3.3)

Python类递归

python - 延长线以平滑连接点

python - Python中是否有文字字符串

python - Matplotlib 中三角形边框的问题

Java Selenium Web 元素变量与 Web 元素数组

selenium - 适用于 Mac M1 的 Chromedriver 107