1

我似乎無法讓Selenium正確運行此for循環。它在沒有問題的情況下第一次運行,但是當它啓動到程序的第二個循環時,就會停止運行並且不會顯示錯誤消息。當我嘗試使用Firefox瀏覽器時,會得到相同的結果。也許它與我試圖啓動一個瀏覽器實例,當一個已經運行?任何幫助將不勝感激。先謝謝了!Selenium不會在for循環中打開一個新的url(Python&Chrome)

def bookroom(self): 
sessionrooms=["611", "618"] #the list being used by the for loop 
     driver = webdriver.Firefox() 
     #for loop trying each room 
     for rooms in sessionrooms: 
      room=roomoptions[rooms][0] 
      sidenum=roomoptions[rooms][1] 
      bookingurl="https://coparooms.newschool.edu/copa-scheduler/Web/reservation.php?rid="+room+"&sid="+sidenum+"&rd="+self.startdate 
      driver.get(bookingurl) 
      time.sleep(3) 
      usernamefield = driver.find_element_by_id("email") 
      usernamefield.send_keys(self.username) 
      passwordfield = driver.find_element_by_id("password") 
      passwordfield.send_keys(self.password) 
      passwordfield.send_keys(Keys.RETURN) 
      time.sleep(5) 
      begin=Select(driver.find_element_by_name("beginPeriod")) 
      print(self.starttime) 
      begin.select_by_visible_text(convertarmy(self.starttime)) 
      end=Select(driver.find_element_by_name("endPeriod")) 
      end.select_by_visible_text(convertarmy(self.endtime)) 
creates=driver.find_element_by_xpath("//button[contains(.,'Create')]") 
      creates.click() #clicks the confirm button 
      time.sleep(8) 
      xpathtest=driver.find_element_by_id("result").text 
      #if statement checks if creation was a success. If it is, exit the browser. 
      if "success" in xpathtest or "Success" in xpathtest: 
       print "Success!" 
       driver.exit() 
      else: 
       print "Failure" 
       time.sleep(2) 
      #if creation was not success try the next room in sessionrooms 

更新: 發現了問題,它只是一個不平坦的間距的問題。只有一些循環「在循環中」。謝謝各位的幫助!

+0

您可以修剪下來的代碼來重現它?也許只是一個循環,它試圖重定向?我不知道所有這些代碼都與你遇到的問題有關。 – TankorSmash

+0

好的,確定!現在不行,但稍後回家時會做。 –

回答

0
if "success" in xpathtest or "Success" in xpathtest: 
    print "Success!" 
    driver.exit() 

你會希望在這裏打破了你的循環,因爲您要關閉驅動器,但在循環的下一次迭代中使用它,而無需啓動一個新的驅動程序對象

+0

當我嘗試在if語句中放置一箇中斷時,控制檯告訴我我在循環的上下文之外使用中斷 –