问题描述
我正在为工作编写自动化程序,并且陷入了下拉菜单。有问题的特定选择框如下: enter image description here
如果没有选择项,我该如何选择其中一项?
解决方法
一个Java语言演示,只需自己翻译成Python(如果不能,请告诉我):
WebElement province = driver.findElement(By.xpath("//*[@id='province']"));
// scroll the page to the element `Provincia`
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView();",province);
// province.click(); doesn't work,I have not figured out why
new Actions(driver).moveToElement(province).click().perform();
// Notice this is the answer to your question
driver.findElement(By.xpath("//ul//li//span[contains(text(),'Granada')]")).click();
,
由于不是选择类型的项目,您可以先单击下拉菜单中的箭头以使可用选项可见。然后,您可以使用Java脚本从下拉菜单中选择所需的选项。我们之所以使用JavaScript,是因为即使单击箭头后也有可能,屏幕上的某些选项可能不在屏幕上。
driver = webdriver.Chrome('..\drivers\chromedriver')
driver.maximize_window()
driver.get("https://www.milanuncios.com/publicar-anuncios-gratis/formulario?c=393")
# Wait for upto 20 sec for page to load completely
WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,"//a[@class='ma-NavigationHeader-logoLink']")))
proviceDropDown = driver.find_element_by_xpath("//input[@id='province']//following-sibling::span")
#Scroll to dropdoen you want to select
driver.execute_script("arguments[0].scrollIntoView();",proviceDropDown)
proviceDropDown.click()
#Assume you are getting province name as parameter,I am doing a static assignment for demonstration
proviceValue = "Granada"
optionToSelectXPath = "//ul[@class='sui-MoleculeDropdownList sui-MoleculeDropdownList--large']//span[text()='"+ proviceValue +"']")"
driver.execute_script("arguments[0].click();",driver.find_element_by_xpath(optionToSelectXPath ))