我正在尝试使用Python和selenium包填写此homepage上的下拉菜单。选择让我使用以下代码
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select
driver = webdriver.Firefox()
driver.implicitly_wait(5)
driver.get('http://www.tirerack.com/content/tirerack/desktop/en/homepage.html')
button = driver.find_element_by_tag_name('button')
ActionChains(driver).click(button).perform()
select_make = driver.find_element_by_id('vehicle-make')
Select(select_make).select_by_value("BMW")
然而,实际上并没有这样做"选择BMW"选项。我尝试按照this帖子中解释的方法进行操作。有人能告诉我我做错了吗?
答案 0 :(得分:0)
从您链接到已接受答案的问题迭代选项并找到匹配的文本。
select_make = driver.find_element_by_id('vehical-make')
for option in select_make.find_elements_by_tag_name('option'):
if option.text == 'BMW':
option.click() # select() in earlier versions of webdriver
break
在Java中运行我得到的信息是元素不可见,所以我强迫它:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.tirerack.com/content/tirerack/desktop/en/homepage.html");
Thread.sleep(3000);
driver.findElement(By.tagName("button")).click();
WebElement select_make = driver.findElement(By.id("vehicle-make"));
select_make.click();
JavascriptExecutor js = (JavascriptExecutor) driver;
String jsDisplay = "document.getElementById(\"vehicle-make\").style.display=\"block\"";
js.executeScript(jsDisplay, select_make);
for (WebElement option : select_make.findElements(By.tagName("option"))) {
System.out.println(option.getText());
if ("BMW".equals(option.getText())) {
option.click();
break;
}
}
如果你添加JavascriptExecutor行(在python中),我认为它会起作用。