线程对我来说很难。在某些事件发生时,我无法完全了解如何停止线程。对我来说很难,因为事件发生在for循环结束时,还涉及浏览器。
此方法应该持续检查标志
def Stop(self, event):
myClass.worker.terminate = True
if myClass.worker != None:
while myClass.browser!=None:
if myClass.worker.taskfinished:
myClass.worker.stop()
myClass.browser.quit()
myClass.worker = None
break
else:
pass
这种情况发生在这个for循环的底部,这是另一种方法的一部分:
for i in range(scraperow, numrows):
myClass.taskfinished = False
domain = sheet.cell_value(i, 2)
prevdomain = sheet.cell_value(i-1,2)
name = sheet.cell_value(i,0)
result = ""
if domain==prevdomain and result=="CATCH-ALL":
worksheet.write(i, 3, "Catch all")
wbook.save(file)
else:
wait = WebDriverWait(self.browser, 500)
inputName = wait.until(EC.presence_of_element_located((By.ID, "form-search-name")))
inputName.send_keys(name)
inputDomain = wait.until(EC.presence_of_element_located((By.ID, "form-search-domain")))
inputDomain.send_keys(domain)
norbertsearch = wait.until(EC.presence_of_element_located((By.NAME, "search")))
norbertsearch.click()
starttime = time.time()
wait = WebDriverWait(self.browser, 500)
selector = "div[class=\"text-center displayed\"] h3"
rslt = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, (selector))))
result = rslt.text
if result == "SUCCESS":
waittwo = WebDriverWait(self.browser, 5)
email = rslt.find_element_by_xpath('following-sibling::div/a')
email = email.get_attribute('href')
email = email.split(":")[1]
worksheet.write(i, 3, email)
wbook.save(file)
elif result == "NOTHING FOUND":
worksheet.write(i, 3, "Nothing found")
wbook.save(file)
elif result == "I'M TIRED":
worksheet.write(i, 3, "Over search limit")
wbook.save(file)
dlg = wx.MessageBox("Norbert is tired and has exhausted his searches for the day. Try again later.", "Ask Alfred", wx.OK | wx.ICON_INFORMATION)
break
elif result == "OH MAN, I BROKE MY ANKLE":
worksheet.write(i, 3, "Server error")
wbook.save(file)
elif result == "CATCH-ALL":
worksheet.write(i, 3, "Catch-all")
wbook.save(file)
myClass.taskfinished = True
不幸的是它阻塞了线程,使事情变得多毛。我如何优雅地让线程等到它得到结果然后停止线程?