Search code examples
pythonseleniumselenium-webdriverformattingstring-formatting

Using Selenium in Python, webscraping using find elements by xpath, .text


I'm trying to automate a task that I have to do every week using Python and Selenium.

I go to a website and if there is any new files I download them, rename them using the date they came in and who they went to, and then place them in a folder on the shared network server.

The website provides the date in which the file comes in through a clickable link.

Using find elements by xpath, and what I assume are parameters, starts with and contains, I've been able to search through all the links with the date and time.

receivedTime = browser.find_elements_by_xpath('//*[starts-with(@id, 
"anchor") and contains(@id, "_0")]')
for time in receivedTime:
 print(time.text)

The output looks like this for example, "11/2/2018, 8:00:50 AM".

I would like to format that text to say "2018-11-02", how would I go about doing that?

It's my understanding that the variable time is just an object of the Current Xpath and .text is just a property of that object. Is my understanding correct?

Thank you.

ANSWER:

receivedTime = browser.find_elements_by_xpath('//*[starts-with(@id, 
"anchor") and contains(@id, "_0")]')
for time in receivedTime:
 date = str(time.text).split(',')
 dateTime = datetime.strptime(date[0], '%m/%d/%Y').strftime('%Y-%m-%d-')
 print(dateTime)

Solution

  • You should use the package datetime (import datetime)
    The time variable is a string so you have to convert it into datetime and change the format like this :

    date = str(time.text).split(',')
    datetime.datetime.strptime(date[0], '%m/%d/%Y').strftime('%Y-%m-%d')