SIM
SIM

Reputation: 22440

Can't write date according to the content of the source

I've written a script in python in combination with selenium to parse some dynamic content from a webpage and write them to a csv file accordingly. The following script can do this errorlessly except for one thing the date.

If you take a look at the content of that site, you can see that there is no year mentioned in that tabular data.

However, when I click on any cell under Date column header in the output file, excel by default count it as the current year whereas the date should be 2004. How can I make the year 2004 according to what is being shown in the below image2?

Script I'm trying with:

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

url = "http://info.nowgoal.com/en/League/2004-2005/36.html"

def get_information(driver,link):
    driver.get(link)
    for items in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'table#Table3 tr')))[2:]:
        try:
            date = items.find_elements_by_css_selector("td")[1].text.split("\n")[0]
            date = datetime.datetime.strptime(date, '%m-%d').strftime('%d-%B')
        except Exception: date = ""
        try:
            match_name = items.find_elements_by_css_selector("td")[2].find_element_by_tag_name("a").text
        except Exception: match_name = ""
        writer.writerow([date,match_name])
        print(date,match_name)

if __name__ == '__main__':
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver,10)
    with open("outputfile.csv","w",newline="") as infile:
        writer = csv.writer(infile)
        writer.writerow(['Date','Match name'])
        try:
            get_information(driver,url)
        finally:  
            driver.quit()

This is how the date are being shown in the csv file: enter image description here

This is what you can see in that webpage:

enter image description here

Upvotes: 1

Views: 62

Answers (1)

Martin Evans
Martin Evans

Reputation: 46769

You could add the correct year to the cell as follows:

import datetime

date = "05-15"
date = datetime.datetime.strptime(date, '%m-%d').replace(year=2004).strftime('%d-%B-%Y')

print(date)

This would display:

15-May-2004

Upvotes: 1

Related Questions