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

时间:2019-01-08 22:22:34

标签: 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。我哪里出错了,谁可以帮我?

3 个答案:

答案 0 :(得分:2)

要检索具有select作为值的us元素的特定选项,可以使用Select硒类执行以下操作:

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'

答案 1 :(得分:2)

要从下拉框中选择America值,请尝试以下代码。它对我有用。

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver=webdriver.Chrome("Path of the Chrome driver" + "chromedriver.exe" )
driver.get("https://invoiceaccess.pgiconnect.com")

select =Select(driver.find_element_by_id("Region"))
select.select_by_value("us")

答案 2 :(得分:0)

使用xpath并选择列表的通用代码

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://invoiceaccess.pgiconnect.com/")
driver.maximize_window()
def ListItemSelection(countrycode):
    driver.find_element_by_xpath("//select/option[@value='" + countrycode + "']").click()

ListItemSelection("us")
time.sleep(1)
ListItemSelection("europe")
time.sleep(1)
ListItemSelection("apac")
time.sleep(1)
driver.quit()