有时候, 我们在用 firepath(不会的请点这里) 查看元素的 XPath 信息, 发现没有可以用来定位的 id 信息, 这个时候我们就需要考虑用其他的可用的来定位元素. 本文介绍如何通过元素节点中 class name 的值来定位页面元素. 还是以百度首页, 搜索输入框定位举例:
XPath 截图
相关脚本代码如下:
- # coding=utf-8
- from selenium import webdriver
- driver = webdriver.Chrome()
- driver.maximize_window()
- driver.implicitly_wait(6)
- driver.get("https://www.baidu.com")
- try:
- driver.find_element_by_class_name("s_ipt")
- print ('test pass: element found by class name')
- except Exception as e:
- print ("Exception found", format(e))
- driver.quit()
意见: 很多情况下, class 利用要比 id 多, 如果 class 中出现了太长的字符, 和可变化的数字, 那么请回到用 XPath 定位方法.
来源: http://www.bubuko.com/infodetail-2893745.html