当与Java驱动程序一起使用时,如何在Selenium中触发单击事件以获取链接?

时间:2012-05-18 11:16:16

标签: java eclipse selenium selenium-rc

我用过

selenium.click("link=Sign In");

我尝试使用

selenium.click(".//*[@id='global-signin']/a");

两者都没有让我得到结果。

我收到如下错误: -

  

Element Link =“登录”未找到错误。

代码:

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", "mcXXX@gmail.com");
        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

    }

}

失败追踪:

 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$1.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$3.run(ParentRunner.java:231)  at
 org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)    at
 org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)  at
 org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)    at
 org.junit.runners.ParentRunner$2.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)

3 个答案:

答案 0 :(得分:3)

之前我也遇到过同样的问题而且找不到元素'问题经常发生在硒中。这个问题的可能原因如下:

  1. 当你执行"点击元素"但是元素没有显示在页面中,也许它在加载的过程中,那么selenium会抛出异常:找不到元素。

  2. 元素的身份错误,可能是拼写错误或者selenium不支持身份识别方式。

  3. 我访问了您测试的网站http://www.washingtonpost.com

    当您导出为Java时,

    SeleniumIDE记录的测试用例始终不起作用。

    这是我的代码:

     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", "adasf@gmail.com");
             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);
             }
         }
     }
    

答案 1 :(得分:1)

<a>元素是动态创建的(并且很糟糕 - 它会在很长一段时间后显示)并且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>

原因在于其中一个js文件中创建了登录链接,如下所示:

I.innerHTML = '<a href="' + D + "...a loong piece of URL..." + H + '">Sign In</a>';

Selenium可以找到动态创建的元素,但只能在创建之后才能找到它。

第一个解决方案,selenium.click("id=global-signin")不起作用,因为找到并单击了该元素,但尚未包含实际链接(由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!");
}

您甚至可以编写自己的click(String)方法(以及其他方法,可以通过代码重复的简单方法,或通过Command pattern更难但更好的方式)将其合并用于每次搜索。

Selenium 2 (WebDriver)中,通过Implicit wait

会更容易
// 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();

答案 2 :(得分:1)

这很难 - 我遇到的问题出现在第二页 - 除非我先选择目标定位器,否则Selenium无法在表单中输入任何数据。这是我的解决方案:

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();
    }

}