我正在尝试使用Selenium WebDriver(2.21.0)点击网页元素。
当我尝试驾驶Selenium IDE时,它可以正常工作,但是当我使用Firefox驱动程序的Java实现尝试相同的一组操作时,它会导致错误的页面。
当代码正在运行并且我手动滚动到所需的元素时,它可以正常工作。
我确保使用
显示和启用网页元素By by = By.xpath("(//a[contains(@href, 'javascript:void(0);')])[26]"); //**Edit:** this is how i
//am getting the locator
WebElement element = driver.findElement(by);
return (element.isEnabled() || element.isDisplayed()) ? element : null;
返回一些元素但不是我期待的元素。
这对我来说很奇怪,因为Selenium webdriver主要滚动到一个元素(如果在屏幕上不可见),并进行所需的交互。
提前致谢!
编辑:这里是IDE的导出代码(java / JUnit4 / webdriver)
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Bandar {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://e.weibo.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testBandar() throws Exception {
driver.get(baseUrl + "/nescafechina");
driver.findElement(By.xpath("(//a[contains(@href, 'javascript:void(0);')])[26]")).click();
driver.findElement(By.xpath("(//a[contains(@href, 'javascript:void(0);')])[12]")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
答案 0 :(得分:1)
Ishank,
我所做的工作已经完成并创建了一个测试,显示了您可以在测试中使用的不同类型的断言。它们看起来与你所看到的有些不同,我觉得你的主要问题是WebElement element = driver.findElement(by);
,因为你没有给它一个实际的元素。 (by);
部分正在查找可在页面上找到的字符串。可接受的字符串是;标识("gbfqb");
或xpath ("(//a[contains(@href, 'javascript:void(0);')])[26]");
或甚至名称("find-button");
。
/**
* Test the main Google page.
* @throws InterruptedException
*
*/
@Test
public void signUp() throws InterruptedException {
String testId = "TestStack01";
entered(testId);
webDriver.get("www.google.com");
webDriver.findElement(By.id("gbqfq")).clear();
webDriver.findElement(By.id("gbqfq")).sendKeys("Test");
assertEquals("", webDriver.findElement(By.id("gbqfb")).getText());
WebElement whatyourlookingfor = webDriver.findElement(By.id("gbqfb"));
assertTrue(selenium.isElementPresent("gbqfb"));
assertTrue(whatyourlookingfor.isEnabled());
assertTrue(whatyourlookingfor.isDisplayed());
assertFalse(whatyourlookingfor.isSelected());
webDriver.findElement(By.id("gbqfb")).click();
leaving(testId);
}
我希望这有助于确定返回哪个元素。
Curtis Miller