user3925023
user3925023

Reputation: 687

Python - Selenium XPATH query mismatch

I've tested an XPATH query using Chrome SelAssist extension and it works pretty fine. The syntax is "//*[@id="fbPhotoSnowliftTimestamp"]/a/abbr":

enter image description here

enter image description here

I've started to write a python code to detect such element:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

chrome_profile = r"C:\Users\XXX\AppData\Local\Google\Chrome\User Data"

options = webdriver.ChromeOptions()

options.add_argument('user-data-dir=' + chrome_profile)

w = webdriver.Chrome(executable_path="C:\\Projects\\selenium\\chromedriver.exe", chrome_options=options)
w.get('https://website.com')    

test = w.find_element(By.XPATH, "//*[@id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")

Page is loaded fine, and it's exactly the same one I've manually tested. Unfortunately I continue to retrieve this error:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="fbPhotoSnowliftTimestamp"]/a/abbr"}
  (Session info: chrome=80.0.3987.149)

I cannot figure out what I'm doing wrong. Thx for any suggestion.

Upvotes: 0

Views: 71

Answers (1)

Jortega
Jortega

Reputation: 3790

The page might not be loading as quickly as expected. A timeout exception will be thrown if the xpath is not found using below. Try:

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

chrome_profile = r"C:\Users\XXX\AppData\Local\Google\Chrome\User Data"

options = webdriver.ChromeOptions()

options.add_argument('user-data-dir=' + chrome_profile)

w = webdriver.Chrome(executable_path="C:\\Projects\\selenium\\chromedriver.exe", chrome_options=options)
w.get('https://website.com')    

test = WebDriverWait(w, 10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")))
#w.find_element(By.XPATH, "//*[@id=\"fbPhotoSnowliftTimestamp\"]/a/abbr")

Upvotes: 1

Related Questions