昨晚在用selenium写网易相册首页(http://photo.163.com)的登录自动化代码时,发现怎么也定位不到登录框的用户名元素,如下图:
代码如下:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Photo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 打开Firefox浏览器
WebDriver driver = new FirefoxDriver();
// 打开163相册
driver.get("http://photo.163.com");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@src='http://blog.163.com/newpage/ursweb/tmpl2/loginurs.html'")));
// 找到页面元素 用户名
// WebElement loginName = driver.findElement(By.name("email"));
WebElement loginName = driver.findElement(By.xpath("//*[@class='j-inputtext dlemail']"));
代码执行到“找到页面元素 用户名”时,就会报错,unable to locate element,定位不到元素。
再仔细查看页面元素结构,发现在上图的iframe下,还有子iframe,如下:
改写代码,加上定位到子iframe的代码:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Photo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 打开浏览器
WebDriver driver = new FirefoxDriver();
// 加上等待时间
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
// 打开163相册
driver.get("http://photo.163.com");
//定位到iframe
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@src='http://blog.163.com/newpage/ursweb/tmpl2/loginurs.html']")));
driver.switchTo().frame(driver.findElement(By.name ("")));
//定位到登录框
WebElement userName = driver.findElement(By.xpath("//*[@class='j-inputtext dlemail']"));
执行后成功定位到登录框元素。
这个问题花了大概1个多小时定位,在未发现子iframe之前,多次更改iframe的格式、登录框的属性值,没有找到问题的根因,有两点心得:
1. 要switch frame时,一定要在查看页面元素时,仔细看一下有几层,嵌套的时候要多条语句定位;
2. 遇到问题时,在多次尝试无果之后,不要死扣(死扣时思维不容易跳出来,不利于发现问题),要停下来分析一下可能的原因,最好从头开始梳理流程,另外就是网上找资料,或者找人问,有些时候别人指导一下,会有“仙人指路”的效果。