【问题标题】:Difficulty in writing xpath using Selenium with Java使用 Selenium 和 Java 编写 xpath 的困难
【发布时间】:2020-04-21 12:01:22
【问题描述】:

在此页面上https://www.bestbuy.ca/en-ca/category/laptops-macbooks/20352(这是笔记本电脑结果页面,其中列出了许多笔记本电脑,我正在尝试获取这台特定的笔记本电脑)

WebElement -- 'HP 15.6" Laptop - Silver (Intel Core i3-1005G1/256GB SSD/8GB RAM/Windows 10)' 使用 xpath 及以下是我的 xpath:

//div[contains(text(),'HP 15.6" Laptop - Silver (Intel Core i3-1005G1/256GB SSD/8GB RAM/Windows 10)')]

此 xpath 正确识别元​​素,但是当我在 eclipse 中粘贴此 xpath 时,它会在 15.6(即 15.6\")之后添加反斜杠 \

xpath("div[contains(text(),'HP 15.6\" Laptop - Silver (Intel Core i3-1005G1/256GB SSD/8GB RAM/Windows 10)')]"))

这就是为什么我的代码会抛出 element not found 异常。谁能帮我解决这个问题。

【问题讨论】:

    标签: java selenium selenium-webdriver xpath


    【解决方案1】:

    15.6\" 是正确的 Eclipse 中显示的内容。因此它会为您转义嵌入的引号。否则它将在 Eclipse IDE 上给出语法错误。由于页面导致失败的原因需要时间来加载元素因此失败。

    诱导WebDriverWait()并等待elementToBeClickable()然后点击。

    new WebDriverWait(driver, 30).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'HP 15.6\" Laptop - Silver (Intel Core i3-1005G1/256GB SSD/8GB RAM/Windows 10)')]"))).click();
    

    【讨论】:

      【解决方案2】:

      你可以使用下面的 xpath 来定位你的 web 元素(python):

      wait = WebDriverWait(driver, 20)
      wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(text(),'HP 15.6" Laptop - Silver (Intel Core i3-1005G1')]")))
      

      注意:请在您的解决方案中添加以下导入

      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      

      如果您使用的是 java,那么您可以使用以下代码来定位您的元素:

      driver.findElement(By.xpath(//div[contains(text(),'HP 15.6" Laptop - Silver (Intel Core i3-1005G1')]));
      

      【讨论】:

        猜你喜欢
        • 2013-03-24
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        相关资源
        最近更新 更多