eclipse 与 Java 驱动程序一起使用时,如何在 Selenium 中为链接触发单击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10651616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trigger click event in Selenium for a link, when used with Java driver?
提问by Mannii88
I used the
我使用了
selenium.click("link=Sign In");
And I tried using the
我尝试使用
selenium.click(".//*[@id='global-signin']/a");
Both didn't yield me the result.
两者都没有给我结果。
I am getting the error as below :-
我收到如下错误:-
Element Link="Sign In" not found error.
元素链接="登录"未找到错误。
Code:
代码:
package package1_IdentifyPageOpened;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
//import java.util.regex.Pattern;
public class PublicClass3 {
/**
* @param args
*/
Selenium selenium;
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.washingtonpost.com/");
selenium.start();
}
@Test
public void testTt4() throws Exception {
selenium.open("/");
selenium.click("link=Sign In");
selenium.type("name=MemberName", "[email protected]");
selenium.type("name=Password", "PPP@123");
selenium.click("name=submit");
selenium.waitForPageToLoad("30000");
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Failure Trace:
故障跟踪:
com.thoughtworks.selenium.SeleniumException: ERROR: Element link=Sign
In not found at
com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:112)
at
com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:106)
at
com.thoughtworks.selenium.DefaultSelenium.click(DefaultSelenium.java:193)
at
package1_IdentifyPageOpened.PublicClass3.testTt4(PublicClass3.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:45)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at
org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner.run(ParentRunner.java:231) at
org.junit.runners.ParentRunner.schedule(ParentRunner.java:60) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at
org.junit.runners.ParentRunner.access public class Website extends SeleneseTestBase {
@BeforeMethod
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.washingtonpost.com/");
selenium.start();
}
@Test
public void testWebsite() throws Exception {
selenium.open("/");
waitFor("link=Sign In");
waitSecomd(3);
selenium.click("link=Sign In");
selenium.waitForPageToLoad("60000");
selenium.type("name=MemberName", "[email protected]");
selenium.type("name=Password", "adfasd");
selenium.click("name=submit");
selenium.waitForPageToLoad("60000");
}
@AfterMethod
public void tearDown() throws Exception {
selenium.stop();
}
public void waitFor(String locator) throws Exception {
for (int second = 0;; second++) {
if (second >= 60)
fail("timeout");
try {
if (selenium.isVisible(locator))
break;
} catch (Exception e) {}
Thread.sleep(1000);
}
}
public void waitSecomd(int n) throws Exception {
for (int second = 0;; second++) {
if (second >= 60)
fail("timeout");
try {
if (second > n - 1)
break;
} catch (Exception e) {}
Thread.sleep(1000);
}
}
}
0(ParentRunner.java:50) at
org.junit.runners.ParentRunner.evaluate(ParentRunner.java:222) at
org.junit.runners.ParentRunner.run(ParentRunner.java:300) at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
采纳答案by LiveJin
I also met the same problem before and 'Element not found' problem is frequently happening in selenium.The possible causes to this problem are as follows:
我之前也遇到过同样的问题,在selenium中经常出现'Element not found'的问题。造成这个问题的可能原因如下:
when you execute "click element",however the element has not show in the page,maybe its in the procedding of loading,then selenium will throw a exception: element not found.
the element's identity is wrong,maybe a spelling error or the selenium does not support the identity way.
当您执行“单击元素”时,但是该元素没有显示在页面中,可能是在加载过程中,然后selenium 会抛出异常:找不到元素。
元素的标识错误,可能是拼写错误或硒不支持标识方式。
I visited the website you tested,http://www.washingtonpost.com
我访问了你测试的网站,http://www.washingtonpost.com
Test-Case recorded by SeleniumIDE
always does not work when you export as Java.
SeleniumIDE
当您导出为 Java 时,由记录的测试用例始终不起作用。
Here is my code:
这是我的代码:
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LoginTest {
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final int PAUSE = 10;
@Test
public void testWebsiteTwo() throws Exception {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(PAUSE, TimeUnit.SECONDS);
driver.get("http://www.washingtonpost.com/");
WebElement signin = driver.findElement(By
.cssSelector("li#global-signin a"));
signin.click();
// this line is crucial so that Selenium can enter the username / password
WebDriver.TargetLocator locator = driver.switchTo();
locator.frame(0);
WebElement name = driver.findElement(By.cssSelector("input#username"));
name.sendKeys(USERNAME);
WebElement password = driver.findElement(By.cssSelector("input#password"));
password.sendKeys(PASSWORD);
WebElement form = driver.findElement(By.cssSelector("form[name=form]"));
form.submit();
Thread.sleep(5000);
driver.close();
}
}
回答by Mark Butler
This was tough - the problem I had was on the second page - Selenium could not enter any data into the form unless I selected a target locator first. Here's my solution:
这很难——我遇到的问题是在第二页——除非我先选择了一个目标定位器,否则 Selenium 无法在表单中输入任何数据。这是我的解决方案:
<div id="utility-wrapper" data-tracking-type="utility">
<ul id="utility-links" class="inline-list">
<li id="global-signin" style="min-width:32px;"></li>
回答by Petr Jane?ek
The <a>
element is created dynamically (and in a bad way - it shows up after a long time) and Selenium can't find it. If you look into the source code of the page, you can only see
该<a>
元素是动态创建的(并且以一种糟糕的方式创建 - 它在很长时间后出现)并且 Selenium 找不到它。如果你查看页面的源代码,你只能看到
I.innerHTML = '<a href="' + D + "...a loong piece of URL..." + H + '">Sign In</a>';
The cause is in one of the js files where the Sign In link is created as follows:
原因是在其中创建登录链接的 js 文件之一中,如下所示:
long targetTime = System.currentTimeMillis() + 10000; // 10 seconds from now
boolean found = false;
while (System.currentTimeMillis() < targetTime && !found) {
if (selenium.isElementPresent("link=Sign In")) {
selenium.click("link=Sign In");
found = true;
}
}
if (!found) {
throw new SeleniumException("Element not found!");
}
Selenium can find a dynamically created element, but only after it is created, not before.
Selenium 可以找到动态创建的元素,但只能在创建之后,而不是之前。
The first solution that comes to head, selenium.click("id=global-signin")
doesn't work because the element is found and clicked, but doesn't yet contain the actual link (which is created by js some time later).
出现的第一个解决方案selenium.click("id=global-signin")
不起作用,因为找到并单击了该元素,但尚未包含实际链接(稍后由 js 创建)。
The solution is to wait for the element to show up:
解决方法是等待元素出现:
// open Firefox
WebDriver driver = new FirefoxDriver();
// set the Implicit wait to 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.washingtonpost.com/");
driver.findElement(By.linkText("Sign In")).click();
you can even write your own click(String)
method (and others too, it's possible either the easy way via code repetition, or the harder but nicer way via the Command pattern) that incorporates this for use in every search.
您甚至可以编写自己的click(String)
方法(以及其他方法,可以是通过代码重复的简单方法,也可以是通过命令模式的更难但更好的方法),将其合并到每次搜索中使用。
In Selenium 2 (WebDriver)it would be much easier to do via Implicit wait:
在Selenium 2 (WebDriver) 中,通过隐式等待会更容易:
##代码##