Sh87
Sh87

Reputation: 326

Difficulty in writing xpath using Selenium with Java

On this page https://www.bestbuy.ca/en-ca/category/laptops-macbooks/20352 (this is Laptop result page where many laptops are listed and I am trying to fetch this particular one)

WebElement -- 'HP 15.6" Laptop - Silver (Intel Core i3-1005G1/256GB SSD/8GB RAM/Windows 10)' using xpath and below is my xpath:

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

This xpath correctly identifies the element but when I paste this xpath in eclipse it add backward slash\ after 15.6(i.e. 15.6\") in

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

and that's why my code throws element not found exception. Can anybody help me to solve this issue.

Upvotes: 2

Views: 114

Answers (2)

SeleniumUser
SeleniumUser

Reputation: 4177

You can use below xpath to locate you web element(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')]")))

Note : please add below imports to your solution

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

if you are using java then you can use below code to locate your element:

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

Upvotes: 1

KunduK
KunduK

Reputation: 33384

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.

Induce WebDriverWait() and wait for elementToBeClickable() and then click.

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

Upvotes: 2

Related Questions