创建一个简单的循环

时间:2021-02-27 22:50:16

标签: python selenium loops webdriver

如何告诉我的代码不要结束并重新开始?
从第一个try:

正在运行 = 真 运行时:

f = open('list.txt', 'r', encoding='utf-8').readlines()
for word in f:
    if word == "\n":
        continue
    
    
driver.find_element_by_xpath(Newtweet_button).click()
sleep(0.5)

   
driver.find_element_by_xpath(message_paste).send_keys(word)
        
try:
    driver.find_element_by_xpath(post_tweet_xpatch).click()
    sleep(1)

except (ElementClickInterceptedException):
    driver.find_element_by_xpath(cross_button).click()

except (NoSuchElementException):
    print("tweet not send")
    driver.find_element_by_xpath(cross_button).click()
    sleep(4)

else:    
    driver.find_element_by_xpath(close_button2).click()  
    sleep(4)
f.close()       

1 个答案:

答案 0 :(得分:0)

使用while循环:

running = True
while running:
    #your code

直到 running 设置为 false 才会停止:running = false

或者你可以计数:

count = 0

while count >= 3:
    #your code
    count += 1

这将使代码运行 3 次。

编辑:要关闭文件,您不需要读取文件变量,如下所示:

 with open('list.txt', 'r', encoding='utf-8') as f:
      file = f.readlines()
      for word in file:
          if word == "\n":
             continue
相关问题