【问题标题】:Create a simple loop创建一个简单的循环
【发布时间】:2021-02-27 22:50:16
【问题描述】:

如何告诉我的代码不要结束并重新开始?
来自第一个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()       

【问题讨论】:

  • 您好,fahad,看起来您添加的代码没有缩进,如果您像文件中显示的那样添加缩进会更容易回答。

标签: python selenium loops webdriver


【解决方案1】:

使用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

【讨论】:

  • 当循环完美运行时,谢谢!
  • 但是我有一个问题我无法使用f.close() 关闭我的 f 文件我收到此错误f.close() AttributeError: 'list' object has no attribute 'close'
  • 很高兴您的循环现在正在工作,您能否向我展示您的代码是什么阻止了您的文件关闭?您可以通过编辑上面的问题来做到这一点
  • 您现在可以查看
  • 这就是为什么代码只读取文本文件的最后一行,并且总是将最后一行作为键发送的原因
猜你喜欢
  • 2011-12-26
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-19
相关资源
最近更新 更多