Home > Enterprise >  How to get time from website on selenium?
How to get time from website on selenium?

Time:12-11

I would like to get the time from: https://www.hko.gov.hk/en/gts/time/clock_e.html

currently my code is:

timeDriver.get("https://www.hko.gov.hk/en/gts/time/clock_e.html")
HKTime = WebDriverWait(timeDriver,3).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div[2]/div/div/div[4]/div/div[2]/div/div[3]'))).text
print(HKTime)

However, it is printing nothing. Any ideas why?

CodePudding user response:

Use visibility_of_element_located() instead of presence_of_element_located() and following css selector to identify the element.

driver.get("https://www.hko.gov.hk/en/gts/time/clock_e.html")

print(WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div#hkoClock_Time'))).get_attribute("innerText"))
print(WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div#hkoClock_Time'))).text)

Or you can use following xpath as well

driver.get("https://www.hko.gov.hk/en/gts/time/clock_e.html")

print(WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, '//div[@id="hkoClock_Time"]'))).get_attribute("innerText"))
print(WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, '//div[@id="hkoClock_Time"]'))).text)

CodePudding user response:

To locate a visible element instead of presence_of_element_located() you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and get_attribute("textContent"):

    driver.get("https://www.hko.gov.hk/en/gts/time/clock_e.html")
    print(WebDriverWait(driver, 7).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div#hkoClock_Time"))).get_attribute("textContent"))
    
  • Using XPATH and text attribute:

    driver.get("https://www.hko.gov.hk/en/gts/time/clock_e.html")
    print(WebDriverWait(driver, 7).until(EC.visibility_of_element_located((By.XPATH, "//div[@id='hkoClock_Time']"))).text)
    
  • Console Output:

    am 07:14:03
    
  • Note : You have to add the following imports :

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