繁体   English   中英

我在将 Python (selenium) 输出保存到 txt 文件时遇到问题

[英]I'm having trouble saving my Python (selenium) output to a txt file

我无法将输出保存到文件中。 我正在使用以下脚本(注意这是一个澳大利亚网站):

from selenium import webdriver
import time

    chrome_path =r"C:\Users\Tom\Desktop\chromedriver.exe"
    driver = webdriver.Chrome(chrome_path)
    driver.get("https://pointsbet.com.au/basketball/NBA")

    time.sleep(2)

    driver.find_element_by_xpath("""/html/body/div[1]/div[2]/sport-competition-component/div[1]/div[2]/div[1]/div/event-list/div[1]/event/div/header/div[1]/h2/a""").click()
    time.sleep(2)


    posts = driver.find_elements_by_class_name("market")
    for post in posts:
        print(post.text)


    with open('output12.txt',mode ='w') as f:
        f.write(str(post))

txt 文件中的输出为:

<selenium.webdriver.remote.webelement.WebElement (session="af079b982b14f33d736b6745ad6e9648", element="0.8397874328987758-6")>

它应该是这样的(取决于当时的网站数据):

正面交锋孟菲斯灰熊队 1.55 迈阿密热火队 2.53 线孟菲斯灰熊队 -4.0 1.92 迈阿密热火队 +4.0 1.92 总分超过 195.5 1.87 低于 195.5 1.96 命名一个投注功能迈克康利和马克加索尔组合获得 41+ 分 2.50

以上是脚本运行时文本的打印方式。

任何帮助都会很棒

谢谢 - 堆栈溢出的新手 - 这太棒了

按如下方式更正您的for循环并判断它是否适合您:注意with open(...) ...必须在for循环内部,而不是外部! 您还需要以append模式打开文件。

for post in posts:
    print(post.text)
    with open('output12.txt',mode ='a') as f:
        f.write(post.text)

正如@Tommy 所指出的,另一种更有效的解决方案可能是:

with open('output12.txt',mode ='w') as f:    
        for post in posts:
            print(post.text)
            f.write(post.text)

这将为您提供您所追求的输出(内联评论)

posts = driver.find_elements_by_class_name("market")

# Open your output file
with open('output12.txt', mode='w') as f:
    # Iterate through the posts list
    for post in posts:
        # Print the output to both the screen and the file
        print(post.text)
        f.write(post.text)

出于某种原因,我无法发布我的问题,所以我想我在这里发表评论。 我需要一些关于在 python 中输出文本的帮助。

我使用 kaldi ASR 训练了一个语言模型,现在我正在尝试将它链接到 vosk API 以制作语音到文本软件。 后端引擎是 kaldi,前端工作涉及 python。 python脚本如下:


from vosk import Model, KaldiRecognizer, SetLogLevel
import os
import wave
import json

fname =  input ( "Enter audio file name: " ) 
wav = ".wav"
txt = ".txt"
transcript = fname + txt
audiofilename = fname + wav

#wav = input( "enter audio filename with extension: " )
wf = wave.open(audiofilename, "rb")
model = Model(".")
rec = KaldiRecognizer(model, wf.getframerate())

results = []
# recognize speech using vosk model

while True:
    data = wf.readframes(4000)

    if len(data) == 0:
        break

    if rec.AcceptWaveform(data):
        part_result = json.loads(rec.Result())
        results.append(part_result)
        print(rec.Result())

    else:
        print(rec.PartialResult())
part_result = json.loads(rec.FinalResult())
results.append(part_result)

# forming a final string from the words
text = ''
for r in results:
    text += r['text'] + ' '

print(f"Vosk thinks you said:\n {text}")         
#print(rec.FinalResult())

# convert list of JSON dictionaries to list of 'Word' objects
list_of_Words = []
for sentence in results:
    if len(sentence) == 1:
        # sometimes there are bugs in recognition 
        # and it returns an empty dictionary
        # {'text': ''}
        continue
    for obj in sentence['result']:
        w = custom_Word.Word(obj)  # create custom Word object
        list_of_Words.append(w)  # and add it to list

wf.close()  # close audiofile

# output to the screen
for word in list_of_words:
    print(word.to_string())``` 

The output is working correctly. Info displayed on Shell is fine.

I cant figure out how to use f.write or similar command to save the shell output (all of it or any particular output I need from the code) and save it to a text file.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM