1

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.

Andersson
  • 51,635
  • 17
  • 77
  • 129
KowaiiNeko
  • 327
  • 6
  • 17
  • I read on [this related SO thread](https://stackoverflow.com/questions/3018848/cannot-redirect-output-when-i-run-python-script-on-windows-using-just-scripts-n) that Python on Windows has an oddity that prevents you from redirecting a script's output to a file, so that's what's causing the error with shell redirection, which really is the truest method of doing what you need to do. – ingernet Mar 16 '18 at 21:12

2 Answers2

3

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()
Andersson
  • 51,635
  • 17
  • 77
  • 129
  • I just tried the code and it did make an output .txt file, but there is nothing inside it, and I got this Traceback (most recent call last): File "d:/Developer/Software/Python/res.py", line 12, in output.write("\n".join([post.text for post in body])) File "D:\Python3\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u02c9' in position 5051: character maps to – KowaiiNeko Mar 16 '18 at 21:33
-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()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61