简体   繁体   中英

How to extract text from time tag with Selenium (Python)

I tried to extract all text from a 'time' tag. The HTML is from this page : https://www.python.org

Here is my code:

event_times = driver.find_elements(By.CSS_SELECTOR, value=".event-widget time")
    
for time in event_times:
    print(time.get_attribute("innerHTML"))

I have this output:

<span class="say-no-more">2021-</span>11-13
<span class="say-no-more">2021-</span>11-15
<span class="say-no-more">2021-</span>11-18
<span class="say-no-more">2021-</span>11-19
<span class="say-no-more">2021-</span>11-24

If I change to :

for time in event_times:    
    print(time.text)

The output:

11-13
11-15
11-18
11-19
11-24

My question : is there a direct way to display all the text contained in the time tag, namely 2021-11-13 , 2021-11-15 , etc...?

Except to separate into two searches (in span for "year" and in time for "month-day"), I don't see how to do this...

To extract all the texts from the <time> tags eg 2021-11-05 , using Selenium and you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.menu>li time")))])
  • Using XPATH :

     print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='menu']/li//time")))])
  • Console Output:

     ['2021-11-05', '2021-11-02', '2021-10-26', '2021-10-19', '2021-10-18', '2021-11-13', '2021-11-15', '2021-11-18', '2021-11-19', '2021-11-24']
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM