我试图使用id单击一个按钮,然后使用类名,然后动态地给出xpath,id。你能否告诉我这段代码的确切xpath
package step_definitions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class sharedshelf {
public WebDriver driver;
public sharedshelf()
{
driver = Hooks.driver;
}
@When("^I press option button$")
public void i_press_option_buttion() throws Throwable {
// Write code here that turns the phrase above into concrete actions
Thread.sleep(5000);
driver.findElement(By.xpath("//button[text()='Edit']")).click();
}
HTML
<button type="button" id="ext-gen494" class=" x-btn-text" tabindex="4">Edit</button>
答案 0 :(得分:0)
当您尝试单击该按钮时,该按钮无法单击。尝试等待按钮可点击。
您还可以使用cssSelector
By.cssSelector("[id*='ext']")
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[id*='ext']")));
button.click();
答案 1 :(得分:0)
在这些情况下单击元素时可能会抛出异常: 如果元素被禁用并且selenium试图单击 - 它不会自动等待直到它可被点击 如果元素不可见/元素不可点击(隐藏在另一个元素下),也会发生这种情况 等待元素可点击的解决方案(在引擎盖下等待直到可见并启用)将不会解决过时元素参考异常 http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp
最好的方法是创建一个这样的方法:
public void TryClick(By by)
{
DateTime timeout = DateTime.Now.AddSeconds(10);
bool clickedSuccessfully = false;
Exception exceptionWhileClick = null;
do
{
try
{
WrappedElement.FindElement(by).Click();
clickedSuccessfully = true;
}
catch (Exception e)
{
// ignored
exceptionWhileClick = e;
}
} while (!clickedSuccessfully && DateTime.Now < timeout);
if (!clickedSuccessfully && exceptionWhileClick != null)
throw exceptionWhileClick;
}