KowaiiNeko
KowaiiNeko

Reputation: 327

outputting python script results into text

I have a want to save my python script's result into a txt file.

My python code

from selenium import webdriver
bro = r"D:\Developer\Software\Python\chromedriver.exe"
driver=webdriver.Chrome(bro)
duo=driver.get('http://www.lolduo.com')
body=driver.find_elements_by_tag_name('tr')

for post in body:
    print(post.text)

driver.close()

Some codes that I've tried

import subprocess

with open("output.txt", "w") as output:
    subprocess.call(["python", "./file.py"], stdout=output);

I tried this code and it only makes a output.txt file and has nothing inside it

D:\PythonFiles> file.py > result.txt

Exception:

UnicodeEncodeError: 'charmap' codec can't encode character '\u02c9' in position 0: character maps to

and only prints out 1/3 of the results of the script into a text file.

Upvotes: 1

Views: 819

Answers (2)

NEPALI PLAYERS
NEPALI PLAYERS

Reputation: 1

You can try this. This Is my Python Code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
import time

bro = r"D:\Developer\Software\Python\chromedriver.exe"
driver = webdriver.Chrome(bro)

driver.get('http://www.lolduo.com')
body = driver.find_elements_by_tag_name('tr') .text
with open('output15.txt', mode='w') as f:
    for post in body:
        print(post)
        f.write(post)
time.sleep(2)
driver.close()

Upvotes: -1

Andersson
Andersson

Reputation: 52665

You can try below code to write data to text file:

from selenium import webdriver

bro = r"D:\Developer\Software\Python\chromedriver.exe"
driver = webdriver.Chrome(bro)

driver.get('http://www.lolduo.com')
body = driver.find_elements_by_tag_name('tr') 

with open("output.txt", "w", encoding="utf8") as output:
    output.write("\n".join([post.text for post in body]))

driver.close()

Upvotes: 3

Related Questions