< H1 > recently, when I was learning the unittest unit test framework, I debugged the test script, and found that in this framework, the switch_to.window, could not always report an error and could not locate the element. I feel that it is because the window plum has been switched normally, and the newcomer asks for advice. Thank you. The code is as follows: < / H1 >
< H1 > main.py < / H1 >
import time
import unittest
import auto_test
suite = unittest.TestSuite()
suite.addTest(auto_test.Python_autotest("get_browser"))
suite.addTest(auto_test.Python_autotest("search"))
suite.addTest(auto_test.Python_autotest("user_login"))
suite.addTest(auto_test.Python_autotest("user_logout"))
if __name__ == "__main__":
runner = unittest.TextTestRunner()
runner.run(suite)
< H1 > auto_test.py < / H1 >
from selenium import webdriver
import time
import unittest
class Python_autotest(unittest.TestCase):
def setUp(self,driver = webdriver.Firefox()):
print("Test is start")
self.driver = driver
def get_browser(self):
self.driver.get("https://www.baidu.com/")
def search(self):
try:
self.driver.find_element_by_xpath("//*[@id="kw"]").send_keys("segmentfault")
self.driver.find_element_by_xpath("//*[@id="su"]").click()
except Exception:
print("No found everything, sorry!")
else:
time.sleep(1)
self.driver.find_element_by_xpath("/html/body/div[1]/div[5]/div[1]/div[3]/div[1]/h3/a").click()
def user_login(self):
self.driver.switch_to.window(self.driver.window_handles[-1])
time.sleep(3)
self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[1]/div[2]/a[1]").click()-sharp
def user_logout(self):
self.driver.quit()
def tearDown(self):
print("Test is finish")
if __name__ == "__main__":
unittest.main()