首页 > 解决方案 > Python / Selenium - 如何为 html 获取正确的 xpath

问题描述

从几天开始,我试图找出网站上按钮的正确 XPATH 是什么。

在此处输入图像描述

这是按钮的html代码:

<div class="rc_library_element_name rc_actionable ia-inline-block" href="reporteditor.phtml?.op=3277&amp;.cr=._%21Mqxtjfi_SFjudmo_SWfssuv&amp;.sess=8Otpr5-9Bz_wpGJTXqAEAPTCP7GkYg..&amp;.done=WvKqgMCoA3IAAEf5xL0AAAAK8">Invoice Detail Report</div>

我尝试了几种方法,例如:

invoice_detail_report = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[2]/div[2]/div[2]/div/div[2]/div[5]/div[2]/div[17]/table/tbody/tr/td[2]/div[1]')))

或者

invoice_detail_report = wait.until(EC.element_to_be_clickable((By.XPATH, '//DIV[@class="rc_library_element_name rc_actionable ia-inline-block"][text()="Invoice Detail Report"]')))

不幸的是,这些都没有奏效。

您能否告知该按钮的正确 xpath 是什么?

非常感谢您的帮助,

问候。

标签: pythonseleniumselenium-webdriverxpathwebdriver

解决方案


要将带有文本的元素定位为Invoice Detail Report并在其上调用click(),您可以使用以下任一策略:

  • XPATH 与文本一起使用:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(.,'Invoice Detail Report')]"))).click()
    
  • XPATH 与属性一起使用:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='c_library_element_name rc_actionable ia-inline-block' and contains(@href,'reporteditor.phtml')]"))).click()
    
  • XPATH 使用所有属性

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='c_library_element_name rc_actionable ia-inline-block' and contains(@href,'reporteditor.phtml') and contains(.,'Invoice Detail Report')]"))).click()
    

推荐阅读