首页 > 解决方案 > 在 .txt 文档中写单词而不重复

问题描述

所以我试图在网站中挑选单词并将它们写.txt在 python 的文档中。每次出现新单词时我都需要这样做,但这不是问题。问题是每次我运行代码时都会.txt重复相同的单词。

这是我的代码:

from selenium import webdriver
import time

options = webdriver.ChromeOptions()
options.add_argument('--profile-directory=Default')
options.add_argument('--user-data-dir=D:/Users/daichi/Desktop/Bot/chrome')
url = 'https://web.whatsapp.com/'
driver = webdriver.Chrome('/Users/daichi/Desktop/Bot/chromedriver/chromedriver', options = options)
words = open("words.txt","r+") 

driver.get(url)
time.sleep(10)
user = driver.find_element_by_xpath('//span[@title="A"]')
user.click()
time.sleep(2)
messages = driver.find_elements_by_xpath('//*[text()[contains(.,"!web")]]')
for message in messages:
   if message.text in words.read():
        print("this word is alrealy on the .txt!")
   elif message.text not in words.read():
        words.write(message.text + "\n")

对不起,我的英语不好,来自巴西的你好。

标签: pythonselenium

解决方案


你总是在读同一个文件。

twetts = ['new 1','new 2','new 2']

for twett in twetts:
    if twett in open('palavras.txt','r').read():
        print("the word is alrealy in the txt")
    else:
        wf = open('palavras.txt','a')
        wf.write(f"{twett}\n")
        wf.close()

推荐阅读