python版 完整xpath转css path
注:针对页面带有shadowRoot xpath无法定位,而复制的js css选择器路径的元素id、class会变时使用此方法,就可以复制完整xpath路径转完整css选择器路径从而定位元素。
selenium shadowRoot 定位
// 重点:一定要加return
device.execute_script('return css选择器路径')
完整xpath转css path
import re
def xpath_as_jsPath(xpath):
"""
python版 xpath转csspath
:param xpath: 必须复制完整xpath可用
:return: css选择器路径
"""
xpath = xpath.replace("//","/MyshadowRoot/")
xpath = xpath.replace("/html/","")
tagNames = xpath.split("/")
jsPath = 'document.querySelector("'
for i,tagName in enumerate(tagNames):
index = None
indexs = re.findall("\d+", tagName)
if "[" in tagName and len(indexs)>0:
index = indexs[0]
tagName = tagName.replace(f"[{index}]","")
if tagName:
if "MyshadowRoot" != tagName:
jsPath+= f"{tagName}:nth-of-type({index})" if index else f"{tagName}"
if len(tagNames) != i+1 and tagNames[i+1] != "MyshadowRoot":
jsPath+= " > "
else:
jsPath += '")'
else:
jsPath+= '.shadowRoot.querySelector("'
return jsPath
if __name__ == '__main__':
xpath = "/html/body/div/div[2]/div/div/div[2]/div/div[1]/div[4]/div/div[1]/kat-date-picker//div"
print(xpath_as_jsPath(xpath))
示例:document.querySelector("body > div > div:nth-of-type(2) > div > div > div:nth-of-type(2) > div > div:nth-of-type(1) > div:nth-of-type(4) > div > div:nth-of-type(1) > kat:nth-of-type(picker) > ").shadowRoot.querySelector(“div”)