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. XAML一些控件的使用

    这节来讲一些XAML中常用控件的使用. Window Window控件是一个基础,它是其它控件的容器,我们可以通过修改其中的一些属性来设置窗体的显示效果,下面说一些最常用的属性: WindowStar ...

  2. Vulkan移植GPUImage(五)从P到Z的滤镜

    现aoce_vulkan_extra把GPUImage里从P到Z的大部分滤镜用vulkan的ComputeShader实现了,也就是最后一部分的移植,整个过程相对前面来说比较简单,大部分我都是直接复制 ...

  3. JAVA基础——运算符号

    运算符(java) 算数运算符:+,-,*,/,%(取余),++,-- 赋值运算符:= 关系运算符:<, >, >= ,<= ,== , != 逻辑运算符:&& ...

  4. [Java] Spring 示例

    (一)IoC/DI 功能 配置解析:将配置文件解析为BeanDefinition结构,便于BeansFactory创建对象 对象创建:BeansFactory 根据配置文件通过反射创建对象,所有类对象 ...

  5. [Java] Hibernate

    背景 持久化技术框架 封装了JDBC做数据库相关功能开发的重复性工作 比如创建连接,关闭连接,把字段逐一映射到属性中等 使用 在数据库中创建表 创建java project 导入hibernate依赖 ...

  6. Linux性能监控与分析之--- CPU

    Linux性能监控与分析之--- CPU 望月成三人关注 2016.07.25 18:16:12字数 1,576阅读 2,837 CPU性能指标 用户进程使用CPU的比率 系统进程使用CPU的比率 W ...

  7. ms5611-01ba03 气压传感器 中英文 数据手册

    中文: https://wenku.baidu.com/view/6f8a861fff00bed5b9f31d53.html 英文: https://wenku.baidu.com/view/fe93 ...

  8. 10.13 nc:多功能网络工具

    nc命令 是一个简单.可靠.强大的网络工具,它可以建立TCP连接,发送UDP数据包,监听任意的TCP和UDP端口,进行端口扫描,处理IPv4和IPv6数据包.     如果系统没有nc命令,那么可以手 ...

  9. NLP文本分类

    引言 其实最近挺纠结的,有一点点焦虑,因为自己一直都期望往自然语言处理的方向发展,梦想成为一名NLP算法工程师,也正是我喜欢的事,而不是为了生存而工作.我觉得这也是我这辈子为数不多的剩下的可以自己去追 ...

  10. 女朋友看了也懂的Kafka(上篇)

    @ 目录 前言:为什么需要Kafka 1.初识kafka 1.1 消息队列的好处: 1.2 消息队列的两种模式 没有消息队列我们怎么做? 传统MQ怎么做? 这时候,Kafka就"闪亮登场&q ...