我想将我的python脚本的结果保存到txt文件中。
我的python代码
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()
我尝试过的一些代码
import subprocess
with open("output.txt", "w") as output:
subprocess.call(["python", "./file.py"], stdout=output);
我尝试了这段代码,它只生成了一个output.txt文件,里面什么都没有
D:\PythonFiles> file.py > result.txt
例外:
UnicodeEncodeError:'charmap'编解码器无法编码字符'\ u02c9' 位置0:字符映射到
并且只将脚本的1/3结果打印到文本文件中。
答案 0 :(得分:2)
您可以尝试以下代码将数据写入文本文件:
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()