A good starting point for learning UnitTest is to record the export script from the selenium IDE. I believe many novice learning selenium also started from IED.
Using an IED to record a script
Export the script, save it as baidu.py, and open it through the Python idle editor. As follows:
From selenium import Webdriver to selenium.webdriver.common.by import by from Selenium.webdriver.common.keys import Key s from selenium.webdriver.support.ui import Select from selenium.common.exceptions import nosuchelementexception Import UnitTest, time, re class Baidu (UnitTest. TestCase): def setUp (self): Self.driver = Webdriver. Firefox () self.driver.implicitly_wait () Self.base_url = "http://www.baidu.com/" Self.verificatio
Nerrors = [] Self.accept_next_alert = True def test_baidu (self): Driver = Self.driver Driver.get (Self.base_url + "/") driver.find_element_by_id ("kw"). Send_keys ("Selenium webdriver") driver.fi nd_element_by_id ("su"). Click () driver.close () def is_element_present (self, how, what): Try:self.
Driver.find_element (By=how, value=what) except Nosuchelementexception, E:return False return True def is_alert_present (self): tRy:self.driver.switch_to_alert () except Noalertpresentexception, E:return False return True def close_alert_and_get_its_text (self): Try:alert = Self.driver.switch_to_alert () alert_
Text = Alert.text if self.accept_next_alert:alert.accept () Else: Alert.dismiss () return alert_text Finally:self.accept_next_alert = True def teardown (sel f): Self.driver.quit () self.assertequal ([], self.verificationerrors) if __name__ = = "__main__": U Nittest.main ()
After joining the unittest frame, it looks a lot more complicated than the script we saw before, except for a few lines in the middle Operation Browser, not to be understood, don't worry, let's analyze the ~!