Diante Cross
Diante Cross

Reputation: 11

How do I stdout all my outputs into one txt file

I am working on a project here a work and I have print lines being displayed for 5+ elements. I need to add all the outputs into a txt file. I was told I can use a for loop but not sure how. What are my best options.

import unittest
from selenium import webdriver
import time
import sys

driver = webdriver.Chrome()

driver.get('website')
driver.maximize_window()

# Displays Time Sheet for Current Day
element = driver.find_element_by_xpath('//*[@id="page-wrapper"]/div[1]/h1')  
# this element is visible

print(element.text)

# Displays Start Time
element = driver.find_element_by_xpath('//*
[@id="pageinner"]/div/div[1]/div/div/div/div[1]/div[2]/div[1]')
print("Start time was at:", element.text)

# Displays End Time
element = driver.find_element_by_xpath('//*
[@id="pageinner"]/div/div[1]/div/div/div/div[4]/div[2]/div[1]')
print("Clocked out as of:", element.text)

# Displays when out to Lunch
element = driver.find_element_by_xpath('//*[@id="page-
inner"]/div/div[1]/div/div/div/div[2]/div[2]/div[1]/h3')
print("I left for Lunch at:", element.text)

# Displays when back from Lunch
element = driver.find_element_by_xpath('//*[@id="page-
inner"]/div/div[1]/div/div/div/div[3]/div[2]/div[1]/h3')
print("I arrived back from Lunch at:", element.text)

# Total Hours for The Day
element = driver.find_element_by_xpath('//*[@id="page-
inner"]/div/div[1]/div/div/div/div[5]/div[2]/div[1]')
print("I was at work for:", element.text)

'''
# Save to txt
sys.stdout = open('file.txt', 'w')
print(element.text)
'''

# Screenshot
# driver.save_screenshot('screenshot.png')


driver.close()

if __name__ == '__main__':
    unittest.main()

At the end Here I need to save all the prints into a txt file for documentation.

Upvotes: 0

Views: 76

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

Selenium 3.5 with Python 3.6.1 bindings provides a simpler way to redirect all the Console Outputs into a log file.

You can create a sub-directory within your Project space by the name Log and start redirecting the Console Outputs into a log file as follows:

# Firefox
driver = webdriver.Firefox(executable_path=r'C:\your_path\geckodriver.exe', log_path='./Log/geckodriver.log')

# Chrome
driver = webdriver.Chrome(executable_path=r'C:\your_path\chromedriver.exe', service_log_path='./Log/chromedriver.log')

# IE
driver = webdriver.Ie(executable_path=r'C:\your_path\IEDriverServer.exe', log_file='./Log/IEdriver.log')

It is worth to mention that the verbosity of the webdriver is easily configurable.

Upvotes: 1

Related Questions