org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element
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的更多相关文章
- 元素无法定位问题 NoSuchElementException: Message: no such element: Unable to locate element 解决方法
定位网页上某个按钮时,总是报错元素定位不到,具体如下:NoSuchElementException: Message: no such element: Unable to locate elemen ...
- 关于xpath语句完全正确,但是页面报错: no such element: Unable to locate element: {"method":"xpath","selector":"xpath"}
之前使用selenium-webdriver来写UI的自动化脚本,发现有一个元素一直无法定位,查看其源码,如下 利用xpathChecker验证了xpath语句的是正确的,但是控制台一直报错: no ...
- 如果遇到找不到元素如何处理? 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路径解决 ...
- 解决Selenium弹出新页面无法定位元素问题(Unable to locate element)
Python 2.7 IDE Pycharm 5.0.3 环境细节详见Python+Selenium+PIL+Tesseract真正自动识别验证码进行一键登录 对于同一页面无法定位元素问题请见姊妹篇解 ...
- Message:Unable to locate element 问题解决方法
Python断断续续学了有一段时间了,总感觉不找个小项目练练手心里没底,哪成想出门就遇到"拦路虎",一个脚本刚写完就运行报错,还好做足了心里准备,尝试自行解决. 或许网上有相关解决 ...
- org.openqa.selenium.NoSuchElementException:
http://www.blogjava.net/qileilove/archive/2014/12/11/421309.html selenium webdriver定位不到元素的五种原因及解决办法 ...
- Selenium定位不到指定元素原因之iframe(unable to locate element)
浏览过程中,图片中的内容可能太小,无法看清,可以>右键>在新标签中打开 Outline 项目原因,需要用selenium实现模拟登陆.模拟上传文件,自然就需要模拟点击[上传]按钮: 模拟点 ...
- selenium+python,解决selenium弹出新页面,无法定位元素的问题(报错:Unable to locate element:元素)
1.问题发生描述: 从一个页面进行点击等操作,页面跳转到第二个页面,对第二个页面中的元素,采取任何措施定位都报错,问题报错点如下: 2.出现问题的原因: 窗口句柄还停留在上一个页面,对于当前新弹出的页 ...
- 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.点击按钮[百度一下] 脚本挺简单的,其给出的应用报错信息如下所示: ...
随机推荐
- vue 访问页面时报错 Failed to compile
这个是因为node-sass没安装好,所以要重新安装 windows下运行命令:npm install node-sass --registry=https://registry.npm.taobao ...
- Django(10)ORM模型介绍
前言 随着项目越来越大,采用写原生SQL的方式在代码中会出现大量的SQL语句,那么问题就出现了: 1.SQL语句重复利用率不高,越复杂的SQL语句条件越多,代码越长.会出现很多相近的SQL语句. 2. ...
- 分布式RPC框架Dubbo实现服务治理:集成Kryo实现高速序列化,集成Hystrix实现熔断器
Dubbo+Kryo实现高速序列化 Dubbo RPC是Dubbo体系中最核心的一种高性能,高吞吐量的远程调用方式,是一种多路复用的TCP长连接调用: 长连接: 避免每次调用新建TCP连接,提高调用的 ...
- Django(19)QuerySet API
前言 我们通常做查询操作的时候,都是通过模型名字.objects的方式进行操作.其实模型名字.objects是一个django.db.models.manager.Manager对象,而Manager ...
- 中国排名前100的IC设计公司
中国排名前100的IC设计公司 北京地区大唐微电子技术有限公司北京北大众志微系统科技有限责任公司北京中星微电子有限公司中国华大集成电路设计中心 北京中电华大电子设计有限责任公司 北京清华同方微电子 ...
- PostgreSQL实现字符串拼接
在日常工作中会遇到将多行的值拼接为一个值展现,如果使用过Oracle数据库,可以使用list_agg的聚合函数来实现.那么PostgreSQL也有这样的功能,函数为string_agg.具体用法如 ...
- Linux常见错误解决办法
1. 程序运行的一些基础知识 1. 编译程序时去哪找头文件? 系统目录:就是交叉编译工具链里的某个 include 目录:也可以自己指定:编译时用 " -I dir "选项指定. ...
- 5.配置IP
静态IP配置 1.NAT模式设置 首先设置虚拟机中NAT模式的选项,打开VMware,点击"编辑"下的"虚拟网络编辑器",设置NAT参数 注意: VMware ...
- MySQL之数据定义语言(DDL)
写在前面 本文中 [ 内容 ] 代表啊可选项,即可写可不写. SQL语言的基本功能介绍 SQL是一种结构化查询语言,主要有如下几个功能: 数据定义语言(DDL):全称Data Definition L ...
- swagger上的接口写入数据库
一.依赖 virtualenv -p python3.6 xx pip install scrapy pip install pymysql 二. 1.创建项目和spider1 scrapy star ...