Home > Mobile >  selenium webdriver unable to find element from its xpath even though the xpath is correct
selenium webdriver unable to find element from its xpath even though the xpath is correct

Time:11-26

I'm trying to get the attributes of a tag using selenium webdriver and using the xpath as a locator. I gave the xpath to the driver and it returned NoSuchElementException, but when I enter the xpath in the "Inspect element" window, it showed that particular tag, which means the locator does exist. So what's wrong with selenium? Its still the same even if I give the full xpath

from selenium import webdriver

driver = webdriver.Chrome('D:\\chromedriver.exe')
driver.get('https://cq-portal.webomates.com/#/login')


element=driver.find_element_by_xpath("//button[@type='button']")
print(element.get_attribute('class'))

driver.quit()

selenium version = 3.141.0

CodePudding user response:

You need to just give wait to load the page. Your code is perfectly fine. Either give hardcode wait like sleep or presence of element. Both will work.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
driver = webdriver.Chrome(PATH)
driver.maximize_window()
wait = WebDriverWait(driver, 20)

driver.get('https://cq-portal.webomates.com/#/login')

wait.until(EC.presence_of_element_located((By.XPATH, "//button[@type='button']")))

element = driver.find_element(By.XPATH, "//button[@type='button']")
print(element.get_attribute('class'))

driver.quit()

Output:

btn btn-md btn-primary btn-block

CodePudding user response:

Loops like you are missing a delay. Please try this:

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

driver = webdriver.Chrome('D:\\chromedriver.exe')
wait = WebDriverWait(driver, 20)

driver.get('https://cq-portal.webomates.com/#/login')

wait.until(EC.visibility_of_element_located((By.XPATH, "//button[@type='button']")))

element=driver.find_element_by_xpath("//button[@type='button']")
print(element.get_attribute('class'))

driver.quit()
  • Related