我正在尝试从下拉菜单中选择一个值。我尝试了很多在这里找到的解决方案,但是没有用,有时我遇到无法滚动查看的错误。
代码试用:
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome() # Optional argument, if not specified will search path.
browser.get('https://dzairannonces.com/posts/create');
mySelectElement = browser.find_element_by_id('parentId')
dropDownMenu = Select(mySelectElement)
我想从下拉菜单中选择一个值,然后从第二个下拉菜单中选择另一个值,当我们选择第一个时出现
我也尝试过此代码,但不起作用
import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
class Drpdowm(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_drpdown(self):
driver = self.driver
driver.maximize_window()
driver.get('https://dzairannonces.com/posts/create')
time.sleep(10) # Let the user actually see something!
s1=Select(driver.find_element_by_id('parentId'))
print(s1.options)
for opt in s1.options:
s1.select_by_value(' 315 ')
def tearDown(self):
self.driver.quit()
答案 0 :(得分:0)
正确的代码应为
s1=Select(driver.find_element_by_id('parentId'))
s1.select_by_value('315')
HTML attributes对于多余的空格或换行符非常严格,您需要提供值准确无误
有关专门用于Select Support的Python WebDriver API,请参见<select>
tags一章
关于整体测试设计,一个不错的主意是实施Page Object Model Design Pattern,它将使您能够拆分UI和测试逻辑,并使您的测试健壮,可靠并且易于重构。有关更多信息,请参见Page Objects一章。
答案 1 :(得分:-1)
要选择一个选项,例如从非 <select>
标签的下拉菜单中,汽车可以使用以下解决方案:
代码块:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://dzairannonces.com/posts/create')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.select2-selection__rendered#select2-parentId-container"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='select2-results']/ul//li[@class='select2-results__option' and contains(., 'Automobiles')]"))).click()
浏览器快照: