org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element(识别不到想要的元素)

想获取到收件箱中包含坚果云的字段

 此处遇见的问题,网页中想要识别的元素在iframe框中,于是不能直接:

driver.findElement(By.id("img_out_995536807")).click();
需要先识别frame,然后再找元素:
 driver.switchTo().frame("login_frame").findElement(By.id("img_out_995536807")).click();
package com.xp.climb.selenium;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver; public class LoginRenren { public static void main(String[] args) throws IOException, InterruptedException {
//geckodriver配置
System.setProperty("webdriver.chrome.driver", "E:\\selenium\\chromedriver.exe");
//声明使用的是谷歌浏览器
ChromeDriver driver = new ChromeDriver();
//使用谷歌浏览器打开QQ邮箱网页
driver.get("https://mail.qq.com/");
//元素定位,提交用户名以及密码 driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.switchTo().frame("login_frame").findElement(By.id("img_out_995536807")).click();
// driver.findElementByName("u").clear(); //清空后输入
// driver.findElementByName("u").sendKeys("11");
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// driver.findElementById("p").clear(); //清空后输入
// driver.findElementById("p").sendKeys("11");
// //元素定位,点击登陆按钮
// driver.findElementById("login_button").click();
Thread.sleep(10*1000); //休息一段时间,使得网页充分加载。注意这里非常有必要
Set<Cookie> cookies = driver.manage().getCookies();
//获取登陆的cookies
String cookieStr = "";
for (Cookie cookie : cookies) {
cookieStr += cookie.getName() + "=" + cookie.getValue() + "; ";
}
System.out.println(cookieStr);
//基于Jsoup,使用cookies请求个人信息页面
Response orderResp = Jsoup //添加一些header信息
.connect("https://mail.qq.com/cgi-bin/frame_html?sid=P5g0fdIbJnC1THcX&r=3955f00b3eaae54686461e267bbfc07f")
// .header("Host", "www.renren.com")
.header("Connection", "keep-alive")
.header("Cache-Control", "max-age=0")
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8")
// .header("Origin", "http://www.renren.com")
.header("Referer", "https://mail.qq.com/")
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept-Encoding", "gzip, deflate, br")
.header("Upgrade-Insecure-Requests", "1")
.cookie("Cookie", cookieStr)
.execute();
//解析数据
Document doc = orderResp.parse();
System.out.println(doc);
org.jsoup.select.Elements elements = doc.select("td[class=gt]")
.select("div[class=tf no]");
for (Element element : elements) {
if (element.text().contains("坚果云")) {
System.out.println(element.text());
}
}
driver.quit(); // 关闭浏览器
}
}

总结:

selenium webdriver定位不到元素的五种原因及解决办法 

1.动态id定位不到元素

  for example:

  //WebElement xiexin_element = driver.findElement(By.id("_mail_component_82_82"));

  WebElement xiexin_element = driver.findElement(By.xpath("//span[contains(.,'写 信')]"));

  xiexin_element.click();

  上面一段代码注释掉的部分为通过id定位element的,但是此id“_mail_component_82_82”后面的数字会随着你每次登陆而变化,此时就无法通过id准确定位到element。

  所以推荐使用xpath的相对路径方法查找到该元素。

 2.iframe原因定位不到元素

  由于需要定位的元素在某一个frame里边,所以有时通过单独的id/name/xpath还是定位不到此元素

  比如以下一段xml源文件:

<iframe id="left_frame" scrolling="auto" frameborder="0" src="index.php?m=Index&a=Menu" name="left_frame" noresize="noresize" style="height: 100%;visibility: inherit; width: 100%;z-index: 1">

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<body class="menuBg">

<div id="menu_node_type_0">

<table width="193" cellspacing="0" cellpadding="0" border="0">

<tbody>

<tr>

<tr>

<td id="c_1">

<table class="menuSub" cellspacing="0" cellpadding="0" border="0" align="center">

<tbody>

<tr class="sub_menu">

<td>

<a href="index.php?m=Coupon&a=SearchCouponInfo" target="right_frame">密码重置</a>

</td>

</tr>

  原本可以通过

  WebElement element = driver.findElement(By.linkText("密码重置"));

  来定位此元素,但是由于该元素在iframe id="left_frame"这个frame里边 所以需要先通过定位frame然后再定位frame里边的某一个元素的方法定位此元素

  WebElement element =driver.switchTo().frame("left_frame").findElement(By.linkText("密码重置"));

  3.不在同一个frame里边查找元素

  大家可能会遇到页面左边一栏属于left_frame,右侧属于right_frame的情况,此时如果当前处在

  left_frame,就无法通过id定位到right_frame的元素。此时需要通过以下语句切换到默认的content

  driver.switchTo().defaultContent();

  例如当前所在的frame为left_frame

  WebElement xiaoshoumingxi_element = driver.switchTo().frame("left_frame").findElement(By.linkText("销售明细"));

  xiaoshoumingxi_element.click();

  需要切换到right_frame

  driver.switchTo().defaultContent();

  Select quanzhong_select2 = new Select(driver.switchTo().frame("right_frame").findElement(By.id("coupon_type_str")));

  quanzhong_select2.selectByVisibleText("售后0小时");

  4. xpath描述错误

  这个是因为在描述路径的时候没有按照xpath的规则来写 造成找不到元素的情况出现

  5.点击速度过快 页面没有加载出来就需要点击页面上的元素

  这个需要增加一定等待时间,显示等待时间可以通过WebDriverWait 和util来实现

  例如:

  //用WebDriverWait和until实现显示等待 等待欢迎页的图片出现再进行其他操作

  WebDriverWait wait = (new WebDriverWait(driver,10));

  wait.until(new ExpectedCondition<Boolean>(){
  public Boolean apply(WebDriver d){
  boolean loadcomplete = d.switchTo().frame("right_frame").findElement(By.xpath("//center/div[@class='welco']/img")).isDisplayed();

  return loadcomplete;

  }

  });

  也可以自己预估时间通过Thread.sleep(5000);//等待5秒 这个是强制线程休息

  6.firefox安全性强,不允许跨域调用出现报错

  错误描述:uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location:

  解决办法:

  这是因为firefox安全性强,不允许跨域调用。

  Firefox 要取消XMLHttpRequest的跨域限制的话,第一

  是从 about:config 里设置 signed.applets.codebase_principal_support = true; (地址栏输入about:config 即可进行firefox设置)

  第二就是在open的代码函数前加入类似如下的代码: try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("Permission UniversalBrowserRead denied."); }

  最后看了乙醇的文章

import java.io.File;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.chrome.ChromeDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

public classButtonDropdown {
public static voidmain(String[] args) throws InterruptedException {
WebDriver dr = newChromeDriver();

File file = newFile("src/button_dropdown.html");

String filePath = "file:///" + file.getAbsolutePath();

System.out.printf("nowaccesss %s \n", filePath);

dr.get(filePath);

Thread.sleep(1000);

// 定位text是watir-webdriver的下拉菜单

// 首先显示下拉菜单

dr.findElement(By.linkText("Info")).click();

(newWebDriverWait(dr, 10)).until(new ExpectedCondition<Boolean>(){
public Booleanapply(WebDriver d){
returnd.findElement(By.className("dropdown-menu")).isDisplayed();

}

});

// 通过ul再层级定位

dr.findElement(By.className("dropdown-menu")).findElement(By.linkText("watir-webdriver")).click();

Thread.sleep(1000);

System.out.println("browser will be close");

dr.quit();

}

}

  然后我自己定位的。

public XiaoyuanactivityPage zipaixiuye(){
driver.navigate().refresh();

luntan.click();

WebDriverWrapper.waitPageLoad(driver,3);

(new WebDriverWait(driver, 10)).until(newExpectedCondition<Boolean>() {
public Boolean apply(WebDriverdriver){
returndriver.findElement(By.className("TFB_sub_li")).isDisplayed();

}

});

driver.findElement(By.className("TFB_sub_li")).findElement(By.linkText("自拍秀")).click();

returnPageFactory.initElements(this.getDriver(),

XiaoyuanactivityPage.class);

}

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element的更多相关文章

  1. 元素无法定位问题 NoSuchElementException: Message: no such element: Unable to locate element 解决方法

    定位网页上某个按钮时,总是报错元素定位不到,具体如下:NoSuchElementException: Message: no such element: Unable to locate elemen ...

  2. 关于xpath语句完全正确,但是页面报错: no such element: Unable to locate element: {"method":"xpath","selector":"xpath"}

    之前使用selenium-webdriver来写UI的自动化脚本,发现有一个元素一直无法定位,查看其源码,如下 利用xpathChecker验证了xpath语句的是正确的,但是控制台一直报错: no ...

  3. 如果遇到找不到元素如何处理? Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"id","selector":"investmentframe"}

    常见几种原因与应对,详细参见http://www.blogjava.net/qileilove/archive/2014/12/11/421309.html 1,动态ID无法找到,用xpath路径解决 ...

  4. 解决Selenium弹出新页面无法定位元素问题(Unable to locate element)

    Python 2.7 IDE Pycharm 5.0.3 环境细节详见Python+Selenium+PIL+Tesseract真正自动识别验证码进行一键登录 对于同一页面无法定位元素问题请见姊妹篇解 ...

  5. Message:Unable to locate element 问题解决方法

    Python断断续续学了有一段时间了,总感觉不找个小项目练练手心里没底,哪成想出门就遇到"拦路虎",一个脚本刚写完就运行报错,还好做足了心里准备,尝试自行解决. 或许网上有相关解决 ...

  6. org.openqa.selenium.NoSuchElementException:

    http://www.blogjava.net/qileilove/archive/2014/12/11/421309.html selenium webdriver定位不到元素的五种原因及解决办法 ...

  7. Selenium定位不到指定元素原因之iframe(unable to locate element)

    浏览过程中,图片中的内容可能太小,无法看清,可以>右键>在新标签中打开 Outline 项目原因,需要用selenium实现模拟登陆.模拟上传文件,自然就需要模拟点击[上传]按钮: 模拟点 ...

  8. selenium+python,解决selenium弹出新页面,无法定位元素的问题(报错:Unable to locate element:元素)

    1.问题发生描述: 从一个页面进行点击等操作,页面跳转到第二个页面,对第二个页面中的元素,采取任何措施定位都报错,问题报错点如下: 2.出现问题的原因: 窗口句柄还停留在上一个页面,对于当前新弹出的页 ...

  9. Selenium2学习-038-firefox、webdriver版本不对称问题解决:org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055

    今天有个朋友在群里问,为何脚本运行不通过,其脚本操作步骤简单描述如下: 1.启动火狐浏览器 2.打开百度 3.查询框输入关键字 4.点击按钮[百度一下] 脚本挺简单的,其给出的应用报错信息如下所示: ...

随机推荐

  1. PHP 下载apk文件

    方式一.public function downApkFile(){ $path = Env::get('root_path')."apk/"; //路径 $file_name = ...

  2. MySQL从库维护经验分享

    前言: MySQL 主从架构应该是最常用的一组架构了.从库会实时同步主库传输来的数据,一般从库可以作为备用节点或作查询使用.其实不只是主库需要多关注,从库有时候也要经常维护,本篇文章将会分享几点从库维 ...

  3. blazor发布之后 刷新404的解决方法

    其实所有单页面应用都一样 只需要在nginx里面配置 location / { root html; index index.html index.htm; rewrite ^/.*/$ / last ...

  4. [bug]mysql: The server time zone value '&#214;&#208;&#185;&#250;&#177;&#234;&#215;&#188;&#202;&#177;&#188;&#228;' is unrecognized or represents more than one time zone

    原因: 时区设置有误 解决: 在mysql中修改时区设置: 或 在JDBC代码中增加时区设置: Connection c = DriverManager.getConnection("jdb ...

  5. Docker——Registry搭建私有镜像仓库

    前言 在 Docker 中,当我们执行 docker pull xxx 的时候,它实际上是从 registry.hub.docker.com 这个地址去查找,这就是Docker公司为我们提供的公共仓库 ...

  6. 7.12-7.19 id、w、who、last、lastb、lastlog

    7.12-7.19 id.w.who.last.lastb.lastlog 目录 7.12 id:显示用户与用户组的信息 7.13 w:显示已登录用户信息 7.14 who:显示已登录用户信息 显示最 ...

  7. openstack总结复习

    一.云计算概念 1.云计算是一种按使用量付费的模式,这种模式提供可用的.便捷的.按需的网络访问, 通过互联网进入可配置的计算资源共享池(资源包括网络,计算,存储,应用软件,服务) 2.云计算所包含的几 ...

  8. 008.Python循环for循环

    for 循环 特指用于遍历容器类型数据,(遍历 循环 迭代 都是一个意思)就是把所有的数据一个一个拿出来的过程, while循环有局限性,不能遍历无序容器数据 setvar = {"a&qu ...

  9. Centos7 搭建vsftpd

    1.安装vsftpd 在线安装:yum -y install vsftpd 离线安装:下载vsftp的rpm包,通过rpm -ivh xxx.rpm安装 2.修改/etc/vsftpd/vsftpd. ...

  10. svg 飞线,源码

    <html> <head> <meta charset="utf-8" /> <meta name="viewport" ...