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.

1
  • I read on this related SO thread 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. Commented Mar 16, 2018 at 21:12

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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 <module> 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 <undefined>
-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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.