聊一聊js中元素定位的方法

  • 聊一聊js中元素定位的方法已关闭评论
  • 56 次浏览
  • A+
所属分类:Web前端
摘要

在做selenium web自动化的时候,有时通过selenium定位不到,或无法操作元素,这个时候就需要通过js来

在做selenium web自动化的时候,有时通过selenium定位不到,或无法操作元素,这个时候就需要通过js来

定位/操作元素,然后通过selenium自带的execute_script()方法去执行js语句。下面介绍几种js的定位方法。

一.ID

id的值都是唯一的,所以当存在id字段时可优先使用

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>      function a(){         alert(document.getElementById("button_id").style.display='block')  //id定位     } </script> <body> <button style="display: none" id="button_id">隐藏</button> <button onclick="a()">点击</button> </body> </html>

二.NAME

name值定位元素的话返回的为list,用下标取值即可。如下通过name定位并执行点击事件。

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>      function a(){         document.getElementsByName("button_name")[0].click()  //name定位     }     function b(){         alert("word")     } </script> <body> <span name="button_name" onclick="b()">隐藏</span> <button onclick="a()">点击</button> </body> </html>

三.TAG_NAME

tag_name对应的便是标签名称,返回的也是list集合。

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>      function a(){          document.getElementsByTagName("input")[0].value="请输入内容"  //输入内容     }  </script> <body> <input> <button onclick="a()">点击</button> </body> </html>

四.CLASS_NAME

class_name对应的值是class,返回list集合

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>      function a(){         alert(document.getElementsByClassName("h2_class")[0].style.backgroundImage)  //classname定位     } </script> <body> <h2 class="h2_class" style="display: block; background-image: url('https://static.geetest.com/captcha_v3/batch/v3/25173/2023-01-3')"></h2> <button onclick="a()">点击</button> </body> </html>

五.CSS

css定位有两个方法,下面一一演示看下。

1.querySelectorAll():返回所有匹配的结果,list集合。

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>     function a(){         document.querySelectorAll("input[name='2']")[1].value="123"  //返回全部     } </script> <body> <div class="liming">     <div>         <input name="2">     </div>     <div>         <input name="2">     </div> </div> <button onclick="a()">点击</button> </body> </html>

2.querySelector():不管匹配结果有多少个,只返回第一个。

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <script>     function a(){         alert(document.querySelector("div[class='liming']>div:nth-child(2)>input").getAttribute("name"))     } </script> <body> <div class="liming">     <div>         <input name="1">     </div>     <div>         <input name="2">     </div> </div> <button onclick="a()">点击</button> </body> </html>

 

 

 

 

 

 

 

 

 

 

 

 

文章来源:https://www.cnblogs.com/lihongtaoya/ ,请勿转载