51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1447|回复: 2
打印 上一主题 下一主题

【转帖】WebDriver拾级而上(18) – 设置元素焦点

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2017-7-14 13:19:53 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

做自动化过程中,有时需要给某个元素设置焦点,在selenium1.0中提供了给元素设置焦点的方法。但是在2.0中并没有该办法。如果是输入框我们可以使用click方法,来设置焦点,但是对于link连接或者button如果通过click方法势必会跳转到另外页面或者提交了页面请求。通过尝试发现,如果在元素上进行右击,也可以设置焦点,但是会弹出一个菜单,这时我们可以通过按下键盘的esc键来取消右击弹出的菜单,这样焦点就可以设置成功了。下面我通过键盘和鼠标事件组合来实现该功能。代码如下:
CODE:
  1. <font size="4">import java.awt.AWTException;
  2. import java.awt.Robot;
  3. import java.awt.event.KeyEvent;
  4. import org.openqa.selenium.By;
  5. import org.openqa.selenium.WebDriver;
  6. import org.openqa.selenium.WebElement;
  7. import org.openqa.selenium.firefox.FirefoxDriver;
  8. import org.openqa.selenium.firefox.FirefoxProfile;
  9. import org.openqa.selenium.interactions.Actions;
  10. import org.openqa.selenium.remote.DesiredCapabilities;
  11. import org.testng.annotations.AfterMethod;
  12. import org.testng.annotations.BeforeMethod;
  13. import org.testng.annotations.Test;

  14. public class TestActive {

  15.     WebDriver driver = null;
  16.     Actions action = null;
  17.     Robot robot = null;

  18.     @BeforeMethod
  19.     public void setUp(){
  20.         try {
  21.             robot = new Robot();
  22.         } catch (AWTException e) {
  23.             e.printStackTrace();
  24.         }

  25.         System.setProperty(“webdriver.firefox.bin”, “D:/Firefox/firefox.exe”);
  26.         FirefoxProfile file = new FirefoxProfile();
  27.         DesiredCapabilities ds = DesiredCapabilities.firefox();
  28.         ds.setCapability(FirefoxDriver.PROFILE, file);
  29.         driver = new FirefoxDriver(ds);
  30.         action = new Actions(driver);
  31.     }

  32.     @AfterMethod
  33.     public void tearDown(){
  34.     }

  35.     @Test
  36.     public void start(){
  37.         driver.get(“http://www.baidu.com”);
  38.         driver.manage().window().maximize();
  39.         //查找你需要设置焦点的元素
  40.         WebElement button = driver.findElement(By.xpath(“//*[@id='nv']/a[5]“));
  41.         //对该元素进行右击操作
  42.         action.contextClick(button).perform();
  43.         //按ESC键返回,设置焦点成功
  44.         robot.keyPress(KeyEvent.VK_ESCAPE);
  45.     }
  46. }</font>
复制代码


本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

该用户从未签到

2#
发表于 2017-7-14 15:16:27 | 只看该作者
辛苦了,我的主
回复 支持 反对

使用道具 举报

  • TA的每日心情

    2024-4-19 09:36
  • 签到天数: 942 天

    连续签到: 1 天

    [LV.10]测试总司令

    3#
    发表于 2017-7-17 09:03:18 | 只看该作者
    厉害了  整理这么多
    回复 支持 反对

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-4 16:54 , Processed in 0.066423 second(s), 28 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表