Home > Software design >  Selenium, python, Xpath on youtube, why does it not find the element?
Selenium, python, Xpath on youtube, why does it not find the element?

Time:04-20

I am creating automation tests for a video in YouTube.

def testComment(self):

    time.sleep(2)
    #find comment line
    self.browser.find_element(By.XPATH, '//*[@id="placeholder-area"]').click()
    time.sleep(2)
    #If you have to log, pass
    if self.browser.find_element(By.XPATH, '//input[@id="identifierId"]').is_displayed():
        pass

Ignore sleep, I added it to be sure the page was loaded, but still nothing. What am I doing wrong? The rest of the tests are not failing.

the screenshot of the page and xpath

The error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="placeholder-area"]"}

CodePudding user response:

Thanks guys, it turns out I have to scroll to see the area. Hard scroll like:

browser.execute_script("window.scrollTo(0, 1000)")

You wre great help, I would not think the comments are not loaded without scrolling.

CodePudding user response:

Might be because the comments haven't been loaded yet after 2 seconds. You can try:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def testComment(self):
    #find comment line
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@id="placeholder-area"]'))).click()
    time.sleep(2)
    #If you have to log, pass
    if self.browser.find_element(By.XPATH, '//input[@id="identifierId"]').is_displayed():
        pass

PS: If window width is too small, YouTube comments won't load at all.

  • Related