selenium实战:如何解决无论如何都无法定位的点击展开元素问题

在编写selnium的代码的时候,有时候最郁闷的大概是元素无法定位,而这种无法定位是指,明明通过xpath定位器或者是js的document.getElementByIdx_x,document.getElementBytag等方法提供方法找不到,如多层嵌套的div带data-json的对象,这时候大概唯一方法就是offset了。

1.如果是页面跳转产生的无法定位元素,可以通过 下面的函数解决问题;
public WebDriver switchWebPage() {
WebDriver window = null;
String currentWindow = webdriver.getWindowHandle();
Set handles = webdriver.getWindowHandles();
Iterator it = handles.iterator();
while (it.hasNext()) {
if (currentWindow == it.next())
continue;
window = webdriver.switchTo().window(it.next());
System.out.println("title,url = " + window.getTitle() + ","
+ window.getCurrentUrl());
}
return window;
}
      调用方法为 webdriver.switchWebPage(),就可以跳转到新页面了。

2,如果是frame切换导致的无法定位元素,可以通过下面的实例函数解决问题

public WebElement ScrollInfo() throws InterruptedException {
WebElement frame = webdriver.findElement(By.id("marqueeiframe"));
webdriver.switchTo().frame(frame);
while (!webdriver.findElement(By.linkText("天冷了")).isDisplayed()) {
Thread.sleep(500);
}
return webdriver.findElement(By.linkText("天冷了"));

      先切iframe,再跳转;

3. 如果是隐藏元素,调出js神器。
                     JavascriptExecutor js = (JavascriptExecutor) br.switchWebPage();
           String myjs="br.switchWebPage().findElement(By.cssSelector(\"//img\"))).click()";
         js.executeScript(myjs);

4.如果是在xpath明明显示可以定位元素,但是findElment始终报错,可以通过action提供的相邻识别解决;
                     Actions action = new Actions(br.switchWebPage());
   action.moveToElement(xs.Term().get(9)).moveByOffset(40, 0).click().perform();
   moveToElement先移动到任何一个可以找得到的元素,然后再移动一个相对距离(x,y),本例也即右边40位,可以得到解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值