背景
一句话总结:明明按照网页,写好的代码,但是执行程序时定位不到元素。
原因:很有可能是你要定位的元素的属性是js动态的,即每次打开页面,这个元素的id或者class等元素属性是js动态生成的。代码执行时,元素的属性已经与之前不同,用之前的属性值去定位自然是定位不到的。
解决方法关键字:xpath,contains,starts-with,ends-with
基本思想:根据部分元素属性定位
环境准备
网站找了js动态生成div代码
代码出自https://www.cnblogs.com/lanye/p/3359087.html
点击动态生成DIV.gif
<html>
<body>
<a href="javascript:aa();">click and generate</a>
</body>
</html>
<script language=javascript>
var divId=1;
//动态生成单纯的div
function CreateOuterDiv()
{
var obj=document.createElement("div");
obj.id="myDiv"+divId;
obj.style.border="1px solid #000000";
obj.style.height="30px";
obj.style.width="200px";
obj.style.filter="alpha(opacity=70)";
obj.style.margin="10px";
obj.style.cursor="hand";
obj.algin="center";
//obj.innerHTML="<a href='#"+obj.id+"'>ssssssssss</a>";
obj.innerText="auto_make"+divId;
divId++;
document.body.appendChild(obj);
document.getElementById(obj.id).onclick=function(){aa();};
}
function aa()
{
CreateOuterDiv();//alert();
}
</script>
样例示范
介绍xpath中提供了三个非常好的方法定位部分属性值:
- starts-with 匹配一个属性以开始位置的关键字
- contains 匹配一个属性值中包含的字符串
- ends-with 匹配一个属性以结果位置的关键字
ele = driver.find_elements_by_xpath("//div[start-with(@id,'myDiv')]")
#匹配id以myDiv开头的元素,id='myDiv'
ele = driver.find_elements_by_xpath("//div[contains(@id,'myDiv')]")
#匹配id中含有myDiv的元素,id='myDiv'
当DIV有变化是,python自动打印当前DIV数目,最后DIV数量大于6时程序停止。
from selenium import webdriver
import time
import os
# chromedriver的绝对路径
driver_path = r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
# 初始化一个driver,并且指定chromedriver的路径
driver = webdriver.Chrome(executable_path=driver_path)
#获取本地html绝对地址
f = os.path.abspath('js_demo.html')
# 请求本地网页
driver.get(f)
info =r"//div[contains(@id,'myDiv')]"
e = driver.find_elements_by_xpath(info)
num =len(e)
#循环获取当前DIV
while True:
e = driver.find_elements_by_xpath(info)
# 数量有变化时,打印当前DIV数量
if num != len(e):
print("MyDiv 数目是:"+str(len(e)))
num = len(e)
#当前DIV数量对于6时,退出循环
if len(e) == 6:
break
driver.close()