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

时间:2018-12-15 00:54:53

标签: python selenium selenium-webdriver

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

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

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

任何帮助都会很棒

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

2 个答案:

答案 0 :(得分:0)

按以下步骤纠正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)

答案 1 :(得分:0)

这将为您提供您所关注的输出(内嵌评论)

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)
相关问题