select
元素,其option
元素是动态加载的。 select
不能同时使用。原始代码如下:
public void fillinForm() {
// Fill-in some fields ...
// Select dynamic loaded option
String optionXpath = "//*[@id='field']/option[text()='Software engineering']";
waitForElement(driver, By.xpath(optionXpath), SHORT_TIMEOUT_S);
driver.findElement(By.xpath(optionXpath)).click();
// Fill-in more fields, etc ...
}
// Selenium wait
public static void waitForElement(WebDriver driver, By by, int timeout) {
// implementation
}
新代码变成了某些东西像:
public void setUp() {
page = PageFactory.initElements(driver, Page.class);
}
public void fillinForm() {
page.setField("Software engineering");
}
public class Page {
private webElement field;
public Page setField(String byText) {
field.click();
String optionXpath = String.format("./option[text()='%s']", byText);
field.findElement(By.xpath(optionXpath)).click();
return this;
}
}
如果要在新代码中实现等待,我必须为x4312079q使用xpath,其中包括
option
的xpath,从而丢失使用注释简化代码的优势:public void fillinForm() {
page.setField("Software engineering");
}
public class Page {
private webElement field;
public Page setField(String byText) {
field.click();
// Note that I'm now explicitly writing "field", exactly what I wanted
// to save using annotations and the PageFactory
String optionXpath = String.format("//select[@id='%s']/option[text()='%s']",
"field", byText);
field.findElement(By.xpath(optionXpath)).click();
return this;
}
}
是否可以使用任何注释来等待选项被加载,否则我使用的是错误的吗? br />
#1 楼
在花了更多时间使用WebDriverWait之后,我得到了更好的东西:客户端代码:
/** Page Object. */
public class Page {
private WebElement mySelect;
public Page setMySelect(String optionText) {
String optXpath = String.format("./option[text()='%s']", optionText);
mySelect.click();
waitForOption(driver,mySelect, By.xpath(optXpath), 10)
.click();
}
}
实用程序库:
public class Util {
/**
* Waits until the option targeted by <tt>byOption</tt> is available.
*
* @param select parent element of the option to wait for
* @param byOption selector (relative to the <tt>select</tt>). It will be
* searched calling <tt>select.findElement(byOption)</tt>
* @return option element
*/
public static WebElement waitForOption(
WebDriver driver, WebElement select, By byOption, int seconds) {
Wait<WebDriver> wait = new WebDriverWait(driver, seconds);
return wait.until(new OptionAvailable(select, byOption));
}
public static class OptionAvailable
implements ExpectedCondition<WebElement> {
private WebElement select;
private By byOption;
public OptionAvailable(WebElement select, By byOption) {
this.select = select;
this.byOption = byOption;
}
@Override
public WebElement apply(WebDriver input) {
return select.findElement(byOption);
}
}
}
请注意,使用这种方法(选项为
By
),我们可以将选项作为文本或值来支持。
评论
我现在正在对其进行测试,看来它不起作用:-(连续两次单击(在select和in选项中)以某种方式失败了,不幸的是,调试起来并不容易,因为调试器会干扰正常流。
–阿尔贝托
2011年7月27日17:47
实际上,它可以删除mySelect.click()。我现在有点困惑,因为由于Selenium的问题2112,我被“双击”了。我必须检查如果没有这个“双击”,它是否仍可以在装有Firefox 3.6.18的SUSE Linux Enterprise Server 11中使用
–阿尔贝托
11年7月27日在18:52