Selenium元素定位--Xpath
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="A">
<div id="B">
<div>parent to child</div>
</div>
</div>
</body>
</html>
1、通过开发者工具直接copy
2、串联的方式定位元素;
from selenium import webdriver
from time import sleep
'''
串联查找的方式
'''
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml2.html')
mytext = driver.find_element_by_id('B').find_element_by_tag_name('div').text
print(mytext)
sleep(3)
driver.quit()
3、通过父元素定位子元素;
from selenium import webdriver
from time import sleep
'''
通过父元素定位子元素
'''
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml2.html')
mytext = driver.find_element_by_xpath("//div[@id='B']/div").text
print(mytext)
driver.quit()
from selenium import webdriver
from time import sleep
'''
通过父元素定位子元素,xpath轴
'''
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml2.html')
mytext = driver.find_element_by_xpath("//div[@id='B']/child::div").text
print(mytext)
driver.quit()
4、通过子元素定位父元素;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="A">
<!--子节点定位父节点-->
<div>
<div>child to parent
<div>
<div id="C"></div>
</div>
</div>
</div>
</div>
</body>
</html>
from selenium import webdriver
# "由子节点定位父节点"
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml3.html')
# 1.xpath: `.`代表当前节点; '..'代表父节点
mytext = driver.find_element_by_xpath("//div[@id='C']/../..").text
print(mytext)
# 2.xpath轴 parent
mytext1 = driver.find_element_by_xpath("//div[@id='C']/parent::div/parent::div").text
print(mytext1)
driver.quit()
5、通过弟弟节点定位哥哥节点元素;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--下面两个节点用于兄弟节点定位-->
<div>brother 1</div>
<div id="D"></div>
<div>brother 2</div>
</body>
</html>
from selenium import webdriver
"""
通过弟弟定位哥哥
"""
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml4.html')
# 1.xpath,通过父节点获取其哥哥节点
mytext = driver.find_element_by_xpath("//div[@id='D']/../div[1]").text
print(mytext)
# 2.xpath轴 preceding-sibling
mytext1 = driver.find_element_by_xpath("//div[@id='D']/preceding-sibling::div[1]").text
print(mytext1)
driver.quit()
6、通过哥哥节点定位弟弟节点元素:
from selenium import webdriver
"""
哥哥定位弟弟示例
"""
driver = webdriver.Chrome()
driver.get('E:\XueXi\ZDH\DaiMa\DaiMa\CZBK\one\myhtml4.html')
# 1.xpath,通过父节点获取其弟弟节点
mytext = driver.find_element_by_xpath("//div[@id='D']/../div[3]").text
print(mytext)
# 2.xpath轴 following-sibling
mytext1 = driver.find_element_by_xpath("//div[@id='D']/following-sibling::div[1]").text
print(mytext1)
driver.quit()