繁体   English   中英

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

[英]How to trigger click event in Selenium for a link, when used with Java driver?

我用了

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

我尝试使用

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

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

我收到的错误如下: -

元素链接=“登录”未找到错误。

码:

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)

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

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

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

我访问了您测试的网站, 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);
         }
     }
 }

<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模式更难但更好的方式),并将其合并用于每次搜索。

Selenium 2(WebDriver)中 ,通过隐式等待更容易做到:

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

这很难 - 我遇到的问题是在第二页上 - 除非我先选择目标定位器,否则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();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM