簡體   English   中英

使用 Selenium 和 Java 編寫 xpath 的困難

[英]Difficulty in writing xpath using Selenium with Java

在此頁面上https://www.bestbuy.ca/en-ca/category/laptops-macbooks/20352 (這是筆記本電腦結果頁面,其中列出了許多筆記本電腦,我正在嘗試獲取這台特定的筆記本電腦)

WebElement -- 'HP 15.6" 筆記本電腦 - 銀色 (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 正確識別了元素,但是當我將這個 xpath 粘貼到 eclipse 中時,它會在 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 異常。 誰能幫我解決這個問題。

15.6\" is correct what is showing in eclipse.So it escapes the embedded quotes for you.Otherwise it will give syntax error on Eclipse IDE.The reason it is failing due to page takes time to load the element hence failing.

誘導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();

您可以使用下面的 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')]));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM