![](/img/trans.png)
[英]How to select this element from this non select drop-down menu using Selenium Webdriver and Python
[英]How to select element from drop-down menu via selenium and python?
我正在嘗試通過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'
要從下拉框中選擇值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")
使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.