def test_addpost(): driver = webdriver.Chrome() driver.get("localhost:8000/admin/") elem = driver.find_element_by_id("id_username") elem.send_keys("polarcx") elem = driver.find_element_by_id("id_password") elem.send_keys("polarcx") elem = driver.find_element_by_xpath( "/html/body/div/div[2]/div/form/div[3]/input") elem.click() driver.get("http://localhost:8000/admin/blog/post/add/") elem = driver.find_element_by_name("title") elem.send_keys("test") elem = driver.find_element_by_name("body") elem.send_keys("test1") from selenium.webdriver.support.ui import Select elem = Select(driver.find_element_by_name("categories")) elem.select_by_value('1') elem = driver.find_element_by_name("_save") elem.click()
def registration_new_customer(self): LogFile.logger.info('Registration new customer.') element = self.element_to_be_present(*RegNewCustomer.CREATE_ACC) # Generates different email element.send_keys(str(time.time()) + '@fakemail.org') element = self.browser.find_element(*RegNewCustomer.CREATE_SUBMIT_BTN) element.click() # Fill up ONLY required field element = self.element_to_be_present(*RegNewCustomer.FIRST_NAME) element.send_keys('Vladyslav') element = self.browser.find_element(*RegNewCustomer.LAST_NAME) element.send_keys('Shevchenko') element = self.browser.find_element(*RegNewCustomer.PASSWD) element.send_keys('46464rte.1!@fdfs') element = self.browser.find_element(*RegNewCustomer.ADRESS) element.send_keys('Odessa') element = self.browser.find_element(*RegNewCustomer.CITY) element.send_keys('Odessa') element = Select(self.browser.find_element(*RegNewCustomer.STATE)) element.select_by_value('2') element = self.browser.find_element(*RegNewCustomer.POSTCODE) element.send_keys('65000') element = self.browser.find_element(*RegNewCustomer.PHONE_NUMBER) element.send_keys('1234567890') element = self.browser.find_element(*RegNewCustomer.SUMBIT_BTN) element.click() element = self.browser.find_element(*RegNewCustomer.CHECKOUT_BTN) element.click() time.sleep(Env.vars['wait_time']) LogFile.logger.info('Registration is complete.')
def _select_case(self, role, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(role)) time.sleep(1) checkbox = None wait_until(lambda: self._browser.find_elements_by_css_selector('.tree-node .tree-title') and True) elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title') finder = re.compile(r'.*\b' + case + r'\b') finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b') for elem in elems: action_chains = ActionChains(self._browser) action_chains.move_to_element(elem) action_chains.perform() logger.debug(elem.text) if finder.match(elem.text) or finder_dotted.match(elem.text): parent = elem.find_element_by_xpath('..') checkbox = parent.find_element_by_class_name('tree-checkbox') break if not checkbox: time.sleep(5) raise Exception('Failed to find the case') self._browser.execute_script("$('.overview').css('left', '0')") checkbox.click() time.sleep(1) elem = self._browser.find_element_by_id('runTest') elem.click() if not wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10): raise Exception('Failed to start test case')
def _select_case(self, suite, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(suite)) time.sleep(1) checkbox = None elems = self._browser.find_elements_by_css_selector('.tree-node .tree-title') for elem in elems: action_chains = ActionChains(self._browser) action_chains.move_to_element(elem) action_chains.perform() logger.debug(elem.text) if elem.text.startswith(case): parent = elem.find_element_by_xpath('..') checkbox = parent.find_element_by_class_name('tree-checkbox') break if not checkbox: time.sleep(5) raise Exception('Failed to find the case') checkbox.click() time.sleep(1) elem = self._browser.find_element_by_id('runTest') elem.click() if not self.wait_until(lambda: self._browser.find_element_by_id('stopTest') and True, 10): raise Exception('Failed to start test case')
async def main(): url = 'https://www.seleniumeasy.com/test/basic-first-form-demo.html' driver = webdriver.Chrome( '/Users/mahdikhalilnezhad/PycharmProjects/WebScriping/chromedriver') driver.maximize_window() driver.get(url) # await asyncio.sleep(1) # The code for the email import field search_namad_field = driver.find_element_by_id('user-message') search_namad_field.clear() search_namad_field.send_keys(email) # await asyncio.sleep(1) search_botton = driver.find_element_by_class_name("btn") search_botton.click() # await asyncio.sleep(1) # The code for entering two numbers and displaying their result search_namad_field = driver.find_element_by_id('sum1') search_namad_field.clear() search_namad_field.send_keys(random.randrange(100)) # await asyncio.sleep(1) search_namad_field = driver.find_element_by_id('sum2') search_namad_field.clear() search_namad_field.send_keys(random.randrange(100)) # await asyncio.sleep(1) # element = driver.find_element_by_xpath("//button[@onclick='return']") # element = driver.findElement(By.linkText("Get Total")); element = driver.find_element_by_class_name('btn') element.click() # await asyncio.sleep(1) # Part II of the project url = 'https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html' driver.get(url) # await asyncio.sleep(1) element = driver.find_element_by_id('select-demo') element.click() await asyncio.sleep(1) element = driver.find_element_by_xpath("//select[@id='select-demo']") element = Select(element) element.select_by_value(day) element = driver.find_element_by_class_name('row') element.click() await asyncio.sleep(3) driver.quit()
def create_all_fees(driver, contributions): """Create all fee disbursements in ActBlue contributions. ONLY RUN THIS ONCE per line.""" actblue = 'ActBlue Techincal Services' if not entity_exists(driver, actblue): create_actblue_entity(driver, actblue) get_entity_for_disbursements(driver, actblue) elem = driver.find_element_by_id("SearchResults") if not elem: print("Entity doesn't exist: %s" % actblue) return clicked = False for ee in elem.find_elements_by_tag_name("td"): if ee.text == actblue: ee.parent.find_elements_by_tag_name( 'td')[0].find_element_by_tag_name('a').click() clicked = True break if not clicked: print("Couldn't find matching element for %s" % actblue) return time.sleep(1) # Sleep 1 second so the page loads with open(contributions, 'r') as f: reader = csv.DictReader(f) for row in reader: time.sleep(1) # Sleep 1 second so the page loads fee_date = datetime.strptime( row['Date'], '%Y-%m-%d %H:%M:%S') elem = driver.find_element_by_id('Date') elem.send_keys(fee_date.strftime("%m/%d/%Y")) fee_amount = Decimal(row['Fee']) elem = driver.find_element_by_id('Amount') elem.send_keys("{:.2f}".format(fee_amount)) elem = Select( driver.find_element_by_id('FppcSpendCodeDropDownField')) elem.select_by_value("OFC") elem = driver.find_element_by_id('DescriptionField') elem.send_keys('Service Fee') elem = driver.find_element_by_id('ElectionCycle-input') elem.send_keys('Primary') elem = driver.find_element_by_id('form-submit-button') elem.click()
def _select_case(self, role, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(role)) time.sleep(1) checkbox = None wait_until(lambda: self._browser.find_elements_by_css_selector( '.tree-node .tree-title') and True) elems = self._browser.find_elements_by_css_selector( '.tree-node .tree-title') finder = re.compile(r'.*\b' + case + r'\b') finder_dotted = re.compile(r'.*\b' + case.replace(' ', r'\.') + r'\b') for elem in elems: # elem.txt might be null when the required reference devices could # not be met (either due to the quantity or the type) for specific test. # perform() will throw exceptions if elem.text is null since Chrome # and chromedriver 80. If elem is not shown in current case list # window, move_to_element() will not work either. if not elem.text: continue # execute a javascript to scroll the window to the elem self._browser.execute_script('arguments[0].scrollIntoView();', elem) action_chains = ActionChains(self._browser) action_chains.move_to_element(elem) action_chains.perform() logger.debug(elem.text) if finder.match(elem.text) or finder_dotted.match(elem.text): parent = elem.find_element_by_xpath('..') checkbox = parent.find_element_by_class_name('tree-checkbox') break if not checkbox: time.sleep(5) raise Exception('Failed to find the case') self._browser.execute_script("$('.overview').css('left', '0')") checkbox.click() time.sleep(1) elem = self._browser.find_element_by_id('runTest') elem.click() if not wait_until( lambda: self._browser.find_element_by_id('stopTest') and True, 10): raise Exception('Failed to start test case')
def step(context, tea, excited_about, continent, selenium_commands): tea_element = next(element for element in context.driver.find_elements_by_tag_name("input") if element.get_attribute("value") == tea) tea_element.click() excited_element = next(element for element in context.driver.find_elements_by_name("tool") if element.get_attribute("value") == excited_about) excited_element.click() contitents_select = Select(context.driver.find_element_by_id('continents')) contitents_element = next(element for element in contitents_select.options if element.text==continent) contitents_element.click() another_select_list = Select(context.driver.find_element_by_id('selenium_commands')) another_select_list = next(element for element in another_select_list.options if element.text==selenium_commands) another_select_list.click()
def navigate_to_class(course_number, subject, browser): print('Navigating...') print('Searching for open sections of ' + subject + ' ' + course_number + '.') # Click on "Student Center" elem = browser.find_element_by_id('crefli_HC_SSS_STUDENT_CENTER') elem.click() # Wait to ensure the page has loaded time.sleep(5) # Switch to the iframe frame = browser.find_element_by_id('ptifrmtgtframe') browser.switch_to.frame(frame) # Click on Search elem = browser.find_element_by_id('DERIVED_SSS_SCR_SSS_LINK_ANCHOR1') elem.click() # Wait to ensure the page has loaded time.sleep(5) # Select the Institution elem = Select( browser.find_element_by_id('CLASS_SRCH_WRK2_INSTITUTION$31$')) elem.select_by_visible_text('Baruch College') # Wait to ensure the choice is populated time.sleep(5) # Select CIS elem = Select(browser.find_element_by_id('SSR_CLSRCH_WRK_SUBJECT_SRCH$0')) elem.select_by_visible_text(subject) # Input the course number elem = browser.find_element_by_id('SSR_CLSRCH_WRK_CATALOG_NBR$1') elem.send_keys(course_number) # Click Search elem = browser.find_element_by_id('CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH') elem.click() # Wait to ensure the page has loaded time.sleep(5)
def reload(self): driver = self.driver driver.get("http://asiya.cs.upc.edu/demo/asiya_online.php#") time.sleep(3) driver._switch_to.frame(driver.find_element_by_id("demo-content")) elem = Select(driver.find_element_by_id("input")) elem.select_by_value("raw") elem = driver.find_element_by_id("no_tok") elem.click() elem = Select(driver.find_element_by_id("srclang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("trglang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("srccase")) elem.select_by_value("ci") elem = Select(driver.find_element_by_id("trgcase")) elem.select_by_value("ci") self.driver = driver
def checkRes(): options = Options() options.headless = True driver = webdriver.Firefox(options=options) driver.get("https://www.bseindia.com/corporates/ann.html") elem = Select(driver.find_element_by_id("ddlPeriod")) elem.select_by_visible_text("Result") elem = driver.find_element_by_id("btnSubmit") sleep(1) elem.click() elem.click() sleep(2) updSt = driver.find_element_by_xpath("//*[@id='fontSize']/div[2]/div[2]/div[1]/div[2]").text print(updSt)
def navigate_rbc_download_page(driver): """Click select specific CSV download settings.""" elem = driver.find_element_by_class_name("leftnav-firstpage") elem = elem.find_element_by_xpath("//ul/li/a[text() = 'Download Transactions']") time.sleep(1) elem.click() elem = driver.find_element_by_id("Excel") elem.click() elem = Select(driver.find_element_by_id("transactionDropDown")) elem.select_by_index(1) # 4. Save that csv and then run the usual csv import script elem = driver.find_element_by_id("id_btn_continue") elem.click() print("Downloading file") time.sleep(2)
def test_log(self): driver = self.driver driver.maximize_window() driver.get("http://onspar.pythonanywhere.com/login") driver.find_element_by_xpath("/html/body/div[2]/a[3]").click() elem = driver.find_element_by_name("login") elem.clear() elem.send_keys("vasuparikh") time.sleep(6) elem = driver.find_element_by_name("password") elem.clear() elem.send_keys("vasu95guy") driver.find_element_by_xpath("/html/body/div[3]/div[1]/div/form/div[2]/input[3]").click() time.sleep(7) driver.find_element_by_xpath("/html/body/nav/div/div/ul[1]/li[2]/a").click() time.sleep(3) driver.find_element_by_xpath("/html/body/div[3]/div[1]/a[2]").click() time.sleep(20) elem = Select(driver.find_element_by_id("id_quantity")) elem.select_by_value("2") driver.find_element_by_xpath("/html/body/div[2]/div/div[2]/div[2]/div/div/form/div/div/button").click() time.sleep(5) driver.find_element_by_xpath("/html/body/ul/li[2]/a").click() time.sleep(5) driver.find_element_by_xpath("/html/body/div[2]/a").click() time.sleep(10) driver.find_element_by_xpath("/html/body/form/input[12]").click() time.sleep(15) elem = driver.find_element_by_name("login_email") elem.clear() elem.send_keys("*****@*****.**") time.sleep(15) elem = driver.find_element_by_id("btnNext") elem.click() time.sleep(10) elem = driver.find_element_by_name("login_password") elem.clear() elem.send_keys("test1234") time.sleep(15) elem = driver.find_element_by_id("btnLogin") elem.click() time.sleep(7) elem = driver.find_element_by_id("confirmButtonTop") elem.click() time.sleep(17) elem = driver.find_element_by_id("merchantReturnBtn") elem.click() time.sleep(7) def tearDown(self): self.driver.close()
def login(): go = driver.find_element_by_id("btnConfirm2") go.click() time.sleep(1) #schoolName scName = driver.find_element_by_class_name("searchBtn") scName.click() time.sleep(1) scName = Select(driver.find_element_by_id("sidolabel")) scName.select_by_visible_text(cp_name) scName = Select(driver.find_element_by_id("crseScCode")) scName.select_by_visible_text(sc_level) scName = driver.find_element_by_id("orgname") scName.send_keys(sc_name) scName = driver.find_element_by_class_name("searchBtn") scName.click() scName = driver.find_element_by_class_name("layerSchoolArea") scName.click() scName = driver.find_element_by_xpath("//*[text() = '" + sc_name + "']") scName.click() scName = driver.find_element_by_class_name("layerFullBtn") scName.click() time.sleep(1) #name/DoB id = driver.find_element_by_id("user_name_input") id.send_keys(u_name) id = driver.find_element_by_id("birthday_input") id.send_keys(u_dob) go = driver.find_element_by_id("btnConfirm") go.click() #pw time.sleep(1) pw = driver.find_element_by_class_name("input_text_common") pw.send_keys(u_pw) go = driver.find_element_by_id("btnConfirm") go.click()
def __init__(self): 'stst\resources\linux\chromedriver' # cur_dir = os.path.dirname(__file__) # 'stst/features' # path = os.path.join(cur_dir, 'resources') # print(cur_dir) driver = webdriver.Chrome() driver.get("http://asiya.cs.upc.edu/demo/asiya_online.php#") time.sleep(3) driver._switch_to.frame(driver.find_element_by_id("demo-content")) elem = Select(driver.find_element_by_id("input")) elem.select_by_value("raw") elem = driver.find_element_by_id("no_tok") elem.click() elem = Select(driver.find_element_by_id("srclang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("trglang")) elem.select_by_value("en") elem = Select(driver.find_element_by_id("srccase")) elem.select_by_value("ci") elem = Select(driver.find_element_by_id("trgcase")) elem.select_by_value("ci") self.driver = driver
class elemen: def __init__(self,id): try: self.elem = driver.find_element_by_id(id) except Exception as e: self.elem = driver.find_element_by_link_text(id) def sel(self,opt): self.elem = Select(self.elem) self.elem.select_by_visible_text(opt) def click(self): self.elem.click() def change(self,val): self.elem.send_keys(Keys.CONTROL + "a") self.elem.send_keys(Keys.DELETE) self.elem.send_keys(val) self.elem.send_keys(Keys.RETURN) def printelem(self): print(self.elem)
def setwidget(): '''this is main function for setting widget''' url = "http://codingbee.net/wp-admin/widgets.php" openurl(url) time.sleep(2) scroll_down(400) # Select Custom Menu: $menu_name xpath = "//h3[contains(.,'Custom Menu:') and contains(.,'%s')]" % menu_name el = driver.find_element_by_xpath(xpath) el.click() print(xpath + ' clicked') time.sleep(1) # choose $menu_value from first drop down menu xpath = "//select[contains(@id, 'widget-%s')]" % dropdown_menu_html_id value = menu_value el = Select(driver.find_element_by_xpath(xpath)) el.select_by_visible_text(value) print(xpath + ' clicked') print(value + ' set') time.sleep(1) # Show on checked pages xpath = "//select[contains(@name,'extended_widget_opts-%s')]" % dropdown_menu_html_id value = "Show on checked pages" el = Select(driver.find_element_by_xpath(xpath)) el.select_by_visible_text(value) print(xpath + ' clicked') print(value + ' set') time.sleep(1) scroll_down(200) #click on taxonomies xpath = "//a[contains(@href,'%s-tax')]" % dropdown_menu_html_id el = driver.find_element_by_xpath(xpath) el.click() print(xpath + ' clicked') time.sleep(0.5) #click on Python xpath = "//input[contains(@id, '%s') and contains(@id, 'categories-%s')]" % ( dropdown_menu_html_id, category_html_id) el = driver.find_element_by_xpath(xpath) el.click() print(xpath + ' clicked') time.sleep(1) # save xpath = "//input[contains(@id,'%s-savewidget')]" % dropdown_menu_html_id el = driver.find_element_by_xpath(xpath) print(xpath + ' clicked') el.click()
def login_into_horizon(self): """ first login into Horizon Dashboard """ logging.info("logging into {}".format(self.horizon_login_url)) try: self.driver.get(self.horizon_login_url) pageElement = Select(self.driver.find_element_by_name("auth_type")) if self.auth_type == 'Keystone': pageElement.select_by_value('credentials') #pageElement.select_by_visible_text('Keystone Credentials') pageElement = self.driver.find_element_by_name("username") pageElement.send_keys(self.username) pageElement = self.driver.find_element_by_name("password") pageElement.send_keys(self.password) pageElement = self.driver.find_element_by_css_selector( "button[type='submit']") pageElement.click() else: #pageElement.select_by_value('saml2') pageElement = self.driver.find_element_by_id("loginBtn") pageElement.click() element = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.NAME, "username"))) #pageElement = self.driver.find_element_by_name("Connect") pageElement = self.driver.find_element_by_name("username") pageElement.send_keys(self.username) pageElement = self.driver.find_element_by_name("password") pageElement.send_keys(self.password) pageElement = self.driver.find_element_by_css_selector( "input[type='submit'][value='Login']") pageElement.click() except NoSuchElementException: raise exceptions.PageSourceException("Element not found") navigationStart = self.driver.execute_script( "return window.performance.timing.navigationStart") responseStart = self.driver.execute_script( "return window.performance.timing.responseStart") domComplete = self.driver.execute_script( "return window.performance.timing.domComplete") if "Invalid" in self.driver.page_source: raise exceptions.LoginFailureException('Invalid Username/Password') backendPerformance = responseStart - navigationStart frontendPerformance = domComplete - responseStart totalTime = (backendPerformance + frontendPerformance) logging.info("load time [Login Page] is {} ms".format(totalTime)) return {'Login Page': str(totalTime) + " ms"}
next_btn = driver.find_element_by_css_selector('#next-step') next_btn.click() blank = driver.find_element_by_css_selector('#xmpy') blank.send_keys('L') # 替换成自己的姓名拼音 blank = Select(driver.find_element_by_css_selector('#xyjrm')) blank.select_by_visible_text('非现役军人') # 替换成自己的服役状态 blank = Select(driver.find_element_by_css_selector('#mzm')) blank.select_by_visible_text('汉族') # 替换成自己的民族 blank = driver.find_element_by_css_selector( 'label[for=xbm_1]') # 替换成自己的性别 男生xbm_0 女生xbm_1 blank.click() blank = driver.find_element_by_css_selector( 'label[for=hfm_0]') # 替换成自己的婚姻状态 未婚hfm_0 已婚hfm_1 依次增加 blank.click() blank = Select(driver.find_element_by_css_selector('#zzmmm')) blank.select_by_visible_text('中国共产主义青年团团员') # 替换成自己的政治面貌 blank = driver.find_element_by_css_selector('#txdz') blank.send_keys('北京市朝阳区定福庄东街一号中国传媒大学') # 替换成自己的通信地址 blank = driver.find_element_by_css_selector('#yzbm') blank.send_keys('100024') # 替换成自己的邮编 blank = driver.find_element_by_css_selector('#lxdh')
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from selenium.webdriver.support.ui import Select driver = webdriver.Chrome() driver.get("https://114.by/") assert "Расписание автобусов в Республике Беларусь" in driver.title place_from = driver.find_element_by_css_selector( '[placeholder="введите откуда выезжаем"]') place_from.clear() place_from.send_keys("Минск") select = Select( driver.find_element_by_css_selector( '[.form-route .list-group-item:nth-of-type(1) [href]]')) select.click() place_where = driver.find_element_by_css_selector( '[placeholder="введите куда приезжаем"]') place_where.clear() place_where.send_keys("Лида") time.sleep(1000) driver.close()
for window in windows: driver.close() if __name__ == "__main__": driver = webdriver.Chrome(executable_path="/home/wangbx/Tools/ergwave/chromedriver", service_log_path="/dev/null") driver.get("http://stackoverflow.com") time.sleep(2) if driver.title == "Stack Overflow": print("No need web login") elif "not available" in driver.title: print("Failed") else: if "edirect" in driver.page_source: time.sleep(5) elm = driver.find_element_by_name("user") elm.send_keys("bxwang") elm = driver.find_element_by_name("password") elm.send_keys("123456") elm = Select(driver.find_element_by_name("fqdn")) elm.select_by_visible_text("CSE") driver.set_page_load_timeout(3) elm = driver.find_element_by_name("Login") try: elm.click() except TimeoutException: # which should happen print("Done web login") pass close(driver)
def test_edit_view_project(self): # Given cls = self.__class__ root = cls.root browser = cls.browser ui = cls.ui data_path = os.path.join(root, 'test') self.wait = WebDriverWait(browser, 20) # When # Create a new project. self._get('new-project').click() # Set the name. e = self._get('edit-name') e.clear() e.send_keys('test1') # Set the path. self._get('edit-path').send_keys(data_path) # Setup the tags. self._get('remove-tag-0').click() e = self._get('new-tag') e.send_keys('comments, count, processed') self._get('add-tag').click() e = self._get('tag-type-1') e = Select(e) e.select_by_visible_text('int') e = Select(browser.find_element_by_id('tag-type-2')) e.select_by_visible_text('bool') self._get('new-extension').send_keys('.txt') self._get('add-extension').click() self._wait_while(lambda: len(ui.editor.extensions) == 0) # Save changes. self._get('apply').click() p = ui.vixen.projects[0] self._wait_while(lambda: len(p.last_save_time) == 0) # Then self.assertEqual(len(ui.vixen.projects), 1) self.assertEqual(p.name, 'test1') self.assertEqual(p.root.path, data_path) self.assertEqual(p.tags[0].name, 'comments') self.assertEqual(p.tags[1].name, 'count') self.assertEqual(p.tags[2].name, 'processed') self.assertEqual(p.tags[1].type, 'int') self.assertEqual(p.tags[2].type, 'bool') self.assertEqual(p.number_of_files, 4) m = p.get('root.txt') self.assertEqual(m.relpath, 'root.txt') self.assertEqual(m.type, 'text') self.assertEqual(len(m.tags), 3) # Test control-s last_save = p.last_save_time e = self._get('edit-name') e.clear() e.send_keys('Project 1') e = browser.find_element_by_id('apply') e.send_keys(Keys.CONTROL, "s") self._wait_while(lambda: p.last_save_time == last_save) # Then self.assertEqual(p.name, 'Project 1') # When # Now view the project. self._get('view-0').click() # Navigate down a directory. e = self._get('path-0').click() viewer = ui.viewer self._wait_while(lambda: viewer.current_dir.name == 'test') self.assertTrue('sub' in viewer.current_dir.name) self.assertEqual(ui.mode, 'view') e = self._get('go-to-parent') e.send_keys('') time.sleep(0.2) e.click() browser.find_element_by_id('go-to-parent').click() self._wait_while(lambda: viewer.current_dir.name == 'sub') self.assertEqual(viewer.current_dir.name, 'test') e = self._get('path-2') e.click() self._wait_while(lambda: viewer.current_file is None) self.assertEqual(viewer.current_file.name, 'root.txt') # Change some tag information and save. last_save = p.last_save_time e = self._get('tag-0') e.send_keys('') e.send_keys('test') self._get('tag-1').clear() self._get('tag-1').clear() self._get('tag-1').send_keys('1') self._get('save').send_keys('') self._get('save').click() if cls.driver == 'firefox': self._get('save').click() self._wait_while(lambda: p.last_save_time == last_save) # Then m = p.get('root.txt') self._wait_while(lambda: m.tags['count'] == 0) self.assertEqual(m.tags['comments'], 'test') self.assertEqual(m.tags['count'], 1) # Change some tag information and save using ctrl+s last_save = p.last_save_time self._get('tag-0').send_keys('2') self._get('tag-1').clear() self._get('tag-1').send_keys('12') self._get('tag-1').clear() self._get('tag-1').send_keys('12') self._get('go-to-parent').send_keys(Keys.CONTROL, "s") self._wait_while(lambda: p.last_save_time == last_save) self.assertEqual(m.tags['comments'], 'test2') self.assertEqual(m.tags['count'], 12) # Now check if search works. self._get('search-text').send_keys('count:12') self._get('search').click() self._wait_while(lambda: not ui.viewer.search_completed) # Then e = self._get('search-item-0') e.click() self._wait_while(lambda: viewer.media is None) self.assertTrue(viewer.media.file_name, 'root.txt') self.assertEqual(ui.viewer.is_searching, True) self.assertEqual(ui.viewer.search_completed, True) self._get('clear-search').click() self._wait_while(lambda: ui.viewer.search_completed) e = self._get('path-2') self.assertEqual(ui.viewer.is_searching, False) # When # Now edit the project. browser.find_element_by_link_text('Home').click() e = self._get('edit-0') e.click() self._wait_while(lambda: ui.editor.project is None) # Then self.assertEqual(ui.mode, 'edit') self.assertEqual(ui.editor.project, ui.vixen.projects[-1]) # When # Finally remove the projects. done = False count = 0 while not done and count < 3: try: e = self._get('remove-0') e.send_keys('') e.click() confirm = browser.switch_to_alert() confirm.accept() done = True except NoAlertPresentException: count += 1 time.sleep(0.1) self._wait_while(lambda: len(ui.vixen.projects) > 0) self.assertEqual(len(ui.vixen.projects), 0)
driver.get("https://opensource-demo.orangehrmlive.com/") element = driver.find_element_by_id("txtUsername") element.send_keys("Admin") element = driver.find_element_by_id("txtPassword") element.send_keys("admin123") element.send_keys(Keys.RETURN) element = driver.find_element_by_id("menu_pim_viewMyDetails") element.click() element = driver.find_element_by_id("btnSave") element.click() element = driver.find_element_by_id("personal_txtEmpFirstName") element.clear() element.send_keys("John1") element = driver.find_element_by_id("personal_txtEmpLastName") element.clear() element.send_keys("Smith1") element = driver.find_element_by_id("personal_txtEmployeeId") element.clear() element.send_keys("JS12345") element = driver.find_element_by_id("personal_optGender_1") element.click() element = Select(driver.find_element_by_id("personal_cmbNation")) element.select_by_visible_text("American") element = driver.find_element_by_id("personal_txtEmpNickName") element.clear() element.send_keys("Johny") element = driver.find_element_by_id("btnSave") element.click()
driver.find_element_by_name("ctl00$ContentPlaceHolder1$DropDownListCCAA")) elem.select_by_visible_text("Castilla-La Mancha") time.sleep(2) elem = Select( driver.find_element_by_name( "ctl00$ContentPlaceHolder1$DropDownListProvincia")) elem.select_by_visible_text("Toledo") elem = Select( driver.find_element_by_name( "ctl00$ContentPlaceHolder1$DropDownListEstacion")) elem.select_by_visible_text("Los Navalmorales") time.sleep(1) elem = driver.find_element_by_name("ctl00$ContentPlaceHolder1$ButtonAgregar") elem.click() elem = driver.find_element_by_name("ctl00$ContentPlaceHolder1$CheckBoxVViento") elem.click() elem = driver.find_element_by_name( "ctl00$ContentPlaceHolder1$CheckBoxListParametros$CheckBoxListParametros_2" ) elem.click() elem = driver.find_element_by_name( "ctl00$ContentPlaceHolder1$CheckBoxListParametros$CheckBoxListParametros_8" ) elem.click() elem = driver.find_element_by_name(
def test_run(self): driver = self.driver driver.implicitly_wait(10) #url = 'https://login.salesforce.com/' url = 'https://na112.lightning.force.com/lightning/page/home' url_base = 'https://na112.lightning.force.com' driver.get(url) driver.maximize_window() username = '******' password = '******' # username = os.environ.get('sfdc_username') login_obj = {'username': '', 'password': '', 'login': ''} elem1 = driver.find_element_by_xpath("//input[@id='username']") elem2 = driver.find_element_by_xpath("//input[@id='password']") elem3 = driver.find_element_by_xpath("//input[@id='Login']") xpath = "//input[@id='username']" login_obj['username'] = elem1 login_obj['password'] = elem2 login_obj['login'] = elem3 login_obj.get('username').send_keys(username) login_obj.get('password').send_keys(password) login_obj.get('login').click() time.sleep(5) # Classic Home Page url = "https://na112.salesforce.com/home/home.jsp" driver.get(url) driver.save_screenshot(r'C:\temp\sfdc\login.png') #Accounts # ===================================================================== driver.get("https://na112.salesforce.com/001/o") time.sleep(5) locator = "new" elem = driver.find_element_by_name(locator) elem.click() # Opportunity Name locator = "opp3" text = f"QA Daily Check- {today()}" elem = driver.find_element_by_id(locator) elem.send_keys(text) # Account Name locator = "opp4" text = "LTE" elem = driver.find_element_by_id(locator) elem.send_keys(text) # Close Date locator = "opp9" text = "09/30/2019" elem = driver.find_element_by_id(locator) elem.send_keys(text) # Stage locator = "opp11" text = "Qualification" elem = Select(driver.find_element_by_id(locator)) elem.select_by_visible_text(text) # Save Button locator = "save" elem = driver.find_element_by_name(locator) elem.click() driver.save_screenshot(r'C:\temp\sfdc\account.png') # elem = driver.find_element_by_link_text('LTE-Product Rule') # elem.click() # elem = driver.find_element_by_partial_link_text('Quotes') # elem.click() # Related Links # ===================================================================== # Opportuity --> Contact Roles # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[3]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # Opportuity --> Quote # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[3]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # # Opportuity --> Product # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[4]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # # Opportuity --> Quote Documents # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[4]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # # Opportuity --> Contract # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[4]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # # Opportuity --> Renewal Contract # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[4]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # # Opportuity --> Note & Attachments # locator = "html/body/div[5]/div[1]/section/div/div/div[1]/div[2]/div[1]/div/div[1]/div/header/div[2]/div/div[2]/ul/li[4]/a/div" # elem = driver.find_element_by_xpath(locator) # elem.click() # Buttons # ===================================================================== # Opportunity --> Edit time.sleep(5) locator = "edit" elem = driver.find_element_by_name(locator) elem.click() locator = "opp14" text = "The oppty is created by script" elem = driver.find_element_by_id(locator) elem.send_keys(text) locator = "save" elem = driver.find_element_by_name(locator) elem.click() # locator = "save_new" # elem = driver.find_element_by_name(locator) # elem.click() # locator = "cancel" # elem = driver.find_element_by_name(locator) # elem.click() # # # # Delete # Include Document # Create Order time.sleep(3)
def image_notes(sf_urls,out_table,Editorial_Fine_Print=Editorial_Fine_Print,browser=x.driver): for url in sf_urls: try: start_time = time.time() browser.get('https://na8.salesforce.com/'+ url) md = browser.find_elements_by_class_name('listTitle') temp_wait = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, "00NC0000005L5vx_ileinner"))) buy_button = browser.find_element_by_id('00NC0000005L5vx_ileinner') if ''.join(re.findall('\\b\\d+\\b',md[1].text)) == buy_button.text: print url + '--> : Buy Button Check - Positive' status = 'proceeded' logging.debug('Total No of buy buttons Correct') else: status = 'Declined' sys.exit() logging.debug('Total No of buy buttons Wrong') #add = browser.find_element_by_xpath('//*[@id="006C0000011fvVw_00NC0000004iQvK"]/div[1]/div/div[1]/table/tbody/tr/td[2]/input') add = browser.find_element_by_xpath('//*[@id="00N80000003LdTG_ileinner"]') doubled_click(add) #WebbrowserWait(browser, 15).until(EC.title_contains("Edition")) image_notes = browser.find_element_by_id('00N80000003LdTG_ileinneredit') copy_old_text = (image_notes.text).encode('ascii', 'ignore') new_text = browser.find_element_by_id('00N80000003LdTG') image_notes_final = WebDriverWait(browser, 15).until(EC.presence_of_element_located((By.ID, "00N80000003LdTG"))) new_text.send_keys(str(copy_old_text) + '\nCMS page complete, no need to remake images') save_image_notes = browser.find_element_by_xpath('//*[@id="InlineEditDialog_buttons"]/input[1]') # input[1] -> Save #sleep(5) doubled_click(save_image_notes) # Field : Repeat Deal rd = browser.find_element_by_id('00N80000004hVCp_ileinner') doubled_click(rd) temp_wait = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "00N80000004hVCp"))) select = Select(browser.find_element_by_id('00N80000004hVCp')) select.select_by_value("Multi-record deal") # Field : Do Not Upload dnup = browser.find_element_by_id('00NC0000005LicT_chkbox') copy_old_text = (dnup.get_attribute('title')).encode('ascii', 'ignore') if copy_old_text == 'Checked': pass else: doubled_click(dnup) #temp_wait = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.ID, "00NC0000005LicT"))) browser.find_element_by_id('00NC0000005LicT').click() # Editorial Fine Print if 'clearance' in (browser.title).lower(): efprint = browser.find_element_by_id('00NC0000005MXTX_ilecell') doubled_click(efprint) #temp_wait = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.ID, "00NC0000005LicT"))) efprint_edit_cell = browser.find_element_by_id('00NC0000005MXTX') en = browser.find_element_by_id('00NC0000005QFSJ_ileinner') if str(en.text) == 'en-US': fine_print_text = Editorial_Fine_Print['fine_print_clearance_us'] else: fine_print_text = Editorial_Fine_Print['fine_print_clearance_ca'] efprint_edit_cell.send_keys(fine_print_text) save_eprint = browser.find_element_by_xpath('//*[@id="InlineEditDialog_buttons"]/input[1]') save_eprint.click() elif 'owned' in (browser.title).lower(): efprint = browser.find_element_by_id('00NC0000005MXTX_ilecell') doubled_click(efprint) #temp_wait = WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.ID, "00NC0000005LicT"))) efprint_edit_cell = browser.find_element_by_id('00NC0000005MXTX') en = browser.find_element_by_id('00NC0000005QFSJ_ileinner') if str(en.text) == 'en-US': fine_print_text = Editorial_Fine_Print['fine_print_owned_us'] else: fine_print_text = Editorial_Fine_Print['fine_print_owned_ca'] efprint_edit_cell.send_keys(fine_print_text) save_eprint = browser.find_element_by_xpath('//*[@id="InlineEditDialog_buttons"]/input[1]') save_eprint.click() else: throws() # CC Done cc = browser.find_element_by_id('00NC0000005Li05_ileinner') doubled_click(cc) select = browser.find_element_by_xpath('//*[@id="datePicker"]/div[2]/div/a') select.click() # Writer Ready cc = browser.find_element_by_id('00N80000003Wtbs_ileinner') doubled_click(cc) select = browser.find_element_by_xpath('//*[@id="datePicker"]/div[2]/div/a') select.click() # Editor Ready cc = browser.find_element_by_id('00N80000003LddW_ileinner') doubled_click(cc) select = browser.find_element_by_xpath('//*[@id="datePicker"]/div[2]/div/a') select.click() # Image Ready cc = browser.find_element_by_id('00N80000003WWQV_ileinner') doubled_click(cc) select = browser.find_element_by_xpath('//*[@id="datePicker"]/div[2]/div/a') select.click() # Deal Set Up cc = browser.find_element_by_id('00N80000003jnLh_ileinner') doubled_click(cc) select = browser.find_element_by_xpath('//*[@id="datePicker"]/div[2]/div/a') select.click() # Multi Deal Checker # Save The Record With Caution """ select = browser.find_element_by_name('inlineEditSave') select.click() """ out_table.add_row([url,status,(time.time() - start_time)]) except Exception as e: # Rollback Proof if e: #select = browser.find_element_by_name('inlineEditCancel') #select.click() print e print out_table
#testing register page x = driver.find_element_by_id('register') x.click() x = driver.find_element_by_name('regfac') x.click() x = driver.find_element_by_name('goback') x.click() x = driver.find_element_by_name('regstu') x.click() x = driver.find_element_by_name("username") x.send_keys("CB.EN.U4CSE17322") x = driver.find_element_by_name("password") x.send_keys("#Hello123") x = driver.find_element_by_name("email") x.send_keys("*****@*****.**") x = driver.find_element_by_name("dob") x.send_keys("01-01-2000") x = Select(driver.find_element_by_name('batch')) x.select_by_visible_text("2018-2022") x = Select(driver.find_element_by_name('dept')) x.select_by_visible_text("CSE") x = Select(driver.find_element_by_name('section')) x.select_by_visible_text("B") x = driver.find_element_by_id('regsub') x.click() driver.quit()
e.select_by_index(int(f.value)) elif f.type == "radio" or f.type == "checkbox": if f.locator_type == "name": e = wait.until( EC.presence_of_all_elements_located( (By.NAME, f.locator_value))) #e = wait.until(EC.elements _to_be_clickable((By.NAME, f.locator_value))) e = driver.find_elements_by_name(f.locator_value) #e[0].click() driver.execute_script("arguments[0].click();", e[0]) elif f.type == "search": if f.locator_type == "xpath": e = wait.until( EC.element_to_be_clickable((By.XPATH, f.locator_value))) #e = driver.find_elements_by_name(f.locator_value) e.click() e.send_keys(Keys.RETURN) elif f.type == "button": #to avoid interaction of spec & lic forms driver.implicitly_wait(5) if f.locator_type == "xpath": e = wait.until( EC.element_to_be_clickable((By.XPATH, f.locator_value))) e.click() if f.value == "SPEC": e = wait.until( EC.element_to_be_clickable((By.NAME, Spec_connector))) e.send_keys(Spec) #add e = driver.find_element_by_xpath(add_spec).click()
def SearchEvent(driver,noindex,url): # Firefox configuration for BrowserStack #desired_cap = {'browser': 'Firefox', 'browser_version': '35.0', 'os': 'Windows', 'os_version': '7', 'resolution': '1024x768'} #driver = webdriver.Remote( #command_executor='http://*****:*****@hub.browserstack.com:80/wd/hub', #desired_capabilities=desired_cap) # Firefox configuration for local driver = webdriver.Firefox() driver.delete_all_cookies() driver.get(url) keywordReportVar="" keywordReportVar2="" keywordReportVar3="" AllTestCasedata="" status="" status1="" # Press Key 'ESCAPE' webElements = driver.find_element_by_xpath("//div[@id='live_events_1153']/div/div/div/div[2]/div/div/div/select").send_keys(Keys.ESCAPE) print "Escape" # Select event in drop-down webElements = Select(driver.find_element_by_xpath("//div[@id='live_events_1153']/div/div/div/div[2]/div/div/div/select")) webElements.select_by_visible_text('Raw') # Capture screen-shot strLink = report.CaptureSnapshot(driver,"Event.png") keywordReportVar+=report.keywordReportMethod(True,1,"Selecting the RAW event","Event has been selected",strLink,"Windows") time.sleep(2) webElements = driver.find_element_by_xpath("//div[@id='live_events_1153']/div/div/div/div[2]/div[3]/div[4]/a") webElements.click() # Capture screen-shot and fetching data from UI strLink = report.CaptureSnapshot(driver,"SearchEvent.png") keywordReportVar2+=report.keywordReportMethod(True,1,"Click on search event","Event has been selected",strLink,"Windows") time.sleep(5) FetchedText = driver.find_element_by_xpath("//*[@id='live_events_1153']/div/div/div/div[3]/span[1]/a").get_attribute("title") FetchedText2 = driver.find_element_by_xpath("//*[@id='live_events_1153']/div/div/div/div[4]/span[1]/a").get_attribute("title") # FetchedText3 = driver.find_element_by_xpath("//*[@id='live_events_1153']/div/div/div/div[5]/span[1]/a").get_attribute("title") print FetchedText print FetchedText2 # print FetchedText3 time.sleep(2) # Verifying data from UI if FetchedText.find("Raw", 0) > -1 and FetchedText2.find("Raw", 0) > -1 : strMsg = "User is able to search any event" status1=True status=True else : strMsg = "User is not able to search the event" status=False status1=False path= "/wsx/"+'EventSearchResult.png' print path driver.save_screenshot(htmlFolderPath+path) print htmlFolderPath keywordReportVar3+=report.keywordReportMethod(status1,1,"Event Search Scenario",strMsg,path,"Windows") #driver.find_element_by_css_selector("a.bgimg.right").click() # Wait for 5 seconds time.sleep(2) # Adding report in html formate TestCaseReportVar=report.testcaseMethod(7,"Event Search",status) AllTestCasedata=TestCaseReportVar+keywordReportVar+keywordReportVar2+keywordReportVar3+"</tbody></table></div>" return AllTestCasedata driver.quit()
time.sleep(SLEEP_SECS) for key,value in shipping_info_next.iteritems(): ele_selector = key ele = driver.find_element_by_id(ele_selector) ele.send_keys(value) # shipping_info_next = { 'speed' : 'speed-std', } time.sleep(SLEEP_SECS) for key,value in shipping_info_next.iteritems(): ele_selector = key ele = driver.find_element_by_id(value) ele.click() #click add to cart time.sleep(SLEEP_SECS) ele_number = 0 add_to_cart_selector = "btn-large" add_to_cart_elements = driver.find_elements_by_class_name(add_to_cart_selector) add_to_cart_elements[ele_number].click() #billing # billing_info_ids = { 'name' : 'Kevin Owocki', 'cc-num' : '4242424242424242', 'cvc' : '123',
class webgui(dut, object): obj = None path = None common_wait_interval = 1 old_retry = 5 driver = None def quit(self): if self.driver: self.driver.quit() def __init__(self, name, attr=None, logger=None, logpath=None, shareData=None): #try: dut.__init__(self, name, attr, logger, logpath, shareData) self.log_file = self.logfile binary = None if FireFox: binary_path = './selenium/webdriver/firefox/' profile_path = None profile = None # webdriver.FirefoxProfile(profile_path) #profile = webdriver.FirefoxProfile() a = FirefoxBinary()._get_firefox_start_cmd() #print(a, 'firefox file!!!!!!!!!!!!!!!!!!') if os.path.exists(binary_path): binary = FirefoxBinary(a) profile = webdriver.FirefoxProfile(binary_path) self.driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile) self.driver.log_file = self.logfile else: self.driver = webdriver.Chrome() #webdriver.Chrome.__init__(self) #webdriver.Firefox.__init__(self,firefox_profile=profile)#, firefox_profile=profile, firefox_binary=)# #except: # webdriver.Chrome.__init__(self) #webdriver.Firefox.__init__(self) if self.attribute.has_key('INTERVAL'): self.common_wait_interval = self.attribute['INTERVAL'] time.sleep(0.5) else: self.common_wait_interval = 1 @retry def set_retry(self, retry_max): global g_retry_counter self.old_retry = g_retry_counter g_retry_counter = retry_max @retry def restore_retry(self): global g_retry_counter g_retry_counter = self.old_retry @retry def xfind(self, path, type): if path is not None: self.path = path if str(type).lower() == 'xpath': function = self.driver.find_element_by_xpath elif str(type).lower() == 'name': function = self.driver.find_element_by_name elif str(type).lower() == 'text': function = self.driver.find_element_by_link_text elif str(type).lower() == 'id': function = self.driver.find_element_by_id self.obj = function(self.path) return self.obj @retry def xsend(self, cmd, path=None, type_by='xpath'): element = self.xfind(path, type_by) element.send_keys(cmd) #time.sleep(1) @retry def xclick(self, xpath=None, type_by='xpath'): element = self.xfind(xpath, type_by) element.click() self.sleep(1) @retry def xclear(self, xpath=None, type_by='xpath'): element = self.xfind(xpath, type_by) element.clear() #time.sleep(1) @retry def xrefill(self, data, xpath, type_by='xpath'): element = self.xfind(xpath, type_by) element.clear() element.send_keys(data) @retry def xselect(self, value, xpath=None, type_by='xpath'): self.obj = Select(self.xfind(xpath, type_by)) self.obj.select_by_visible_text(value) self.sleep(1) @retry def xget(self, url=None): if url is not None: self.curr_url = url self.driver.get(self.curr_url) self.sleep(1) @retry def have_text(self, exp_txt, path, type_by='xpath'): try: elem = self.xfind(path, type_by) if elem.text.find(exp_txt) != -1: return True else: return False except Exception as e: return False def closeSession(self): super(webgui, self).closeSession() self.quit() def xcheck(self, xpath=None, type_by='xpath'): self.obj = self.xfind(xpath, type_by) if not self.obj.is_selected(): self.obj.click() self.sleep(1) def xuncheck(self, xpath=None, type_by='xpath'): self.obj = self.xfind(xpath, type_by) if self.obj.is_selected(): self.obj.click() self.sleep(1) def xswitch_2_pop(self, ): browser = self.driver parent_h = browser.current_window_handle # click on the link that opens a new window handles = browser.window_handles # before the pop-up window closes handles.remove(parent_h) browser.switch_to.window(handles.pop()) # do stuff in the popup # popup window closes browser.switch_to.window(parent_h)
with open('temp_2.csv', 'rb') as f: reader = csv.reader(f) for row in reader: sf_urls.append(''.join(row)) for no,url in enumerate(sf_urls): print no,url #browser.get('https://na8.salesforce.com/'+ url) browser.get(url) try: temp_wait = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, "00N80000003Lv1c_ileinner"))) # Field : Repeat Deal rd = browser.find_element_by_id('00N80000003Lv1c_ileinner') doubled_click(rd) temp_wait = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "00N80000003Lv1c"))) select = Select(browser.find_element_by_id('00N80000003Lv1c')) select.select_by_value("Recommended") select = browser.find_element_by_name('inlineEditSave') select.click() status = 'Done' time.sleep(5) except e: status = 'Declined' time.sleep(5) out_table.add_row([url,status,(time.time() - start_time)]) print out_table print("--- %s seconds ---" % (time.time() - start_time))
def navigate_rbc_login_page(driver, owner): username = os.getenv(f"RBC_{owner}") password = os.getenv(f"RBC_{owner}_PASS") security_questions = get_security_questions(owner) # 2. Sign in using environment vars elem = driver.find_element_by_id("K1") elem.send_keys(username) elem = driver.find_element_by_xpath("//input[@type = 'password']") elem.send_keys(password) elem = driver.find_element_by_xpath("//button[@type = 'submit']") elem.click() # try to enter security_questions answers if they ask try: time.sleep(2) elem = driver.find_element_by_class_name("contentframework-altrow") question_text = elem.text.split(": ")[1] answer_to_use = security_questions[question_text] elem = driver.find_element_by_id("pvqAnswer") elem.send_keys(answer_to_use) time.sleep(1) elem = driver.find_element_by_id("id_btn_continue") elem.click() except (NoSuchElementException, ElementNotInteractableException): time.sleep(2) # Try to accept the "re-enter all your security questions and answers" try: time.sleep(2) elem = driver.find_element_by_id("id_btn_thatwasme") elem.click() elem = driver.find_element_by_class_name("bodyLink") elem.click() elem = driver.find_element_by_id("id_btn_continue") elem.click() # Update persoanl verification questions to the same answer they were before for i in [1, 2, 3]: elem = Select(driver.find_element_by_id(f"pvqlist{i}")) question = [ dropdown_item.text for dropdown_item in elem.options if dropdown_item.text in security_questions.keys() ][0] elem.select_by_visible_text(question) elem = driver.find_element_by_id(f"answer{i}") elem.send_keys(security_questions[question]) elem = driver.find_element_by_id("id_btn_continue") elem.click() # update to pvq confirmation elem = driver.find_element_by_class_name("bodyLink") elem.click() except ( NoSuchElementException, ElementNotInteractableException, ElementNotVisibleException, ): time.sleep(2)
class webgui(dut, object): obj = None path = None common_wait_interval = 1 old_retry = 5 driver = None def quit(self): if self.driver: self.driver.quit() def __init__(self, name, attr =None,logger=None, logpath= None, shareData=None): #try: dut.__init__(self, name,attr,logger,logpath,shareData) self.log_file =self.logfile binary = None if FireFox: binary_path = './selenium/webdriver/firefox/' profile_path =None profile =None# webdriver.FirefoxProfile(profile_path) #profile = webdriver.FirefoxProfile() a = FirefoxBinary()._get_firefox_start_cmd() #print(a, 'firefox file!!!!!!!!!!!!!!!!!!') if os.path.exists(binary_path): binary = FirefoxBinary(a) profile = webdriver.FirefoxProfile(binary_path) self.driver= webdriver.Firefox(firefox_binary=binary,firefox_profile=profile) self.driver.log_file= self.logfile else: self.driver = webdriver.Chrome() #webdriver.Chrome.__init__(self) #webdriver.Firefox.__init__(self,firefox_profile=profile)#, firefox_profile=profile, firefox_binary=)# #except: # webdriver.Chrome.__init__(self) #webdriver.Firefox.__init__(self) if self.attribute.has_key('INTERVAL'): self.common_wait_interval = self.attribute['INTERVAL'] time.sleep(0.5) else: self.common_wait_interval = 1 @retry def set_retry(self, retry_max): global g_retry_counter self.old_retry = g_retry_counter g_retry_counter = retry_max @retry def restore_retry(self): global g_retry_counter g_retry_counter =self.old_retry @retry def xfind(self, path, type): if path is not None: self.path = path if str(type).lower() == 'xpath': function = self.driver.find_element_by_xpath elif str(type).lower() == 'name': function = self.driver.find_element_by_name elif str(type).lower() == 'text': function = self.driver.find_element_by_link_text elif str(type).lower() == 'id': function = self.driver.find_element_by_id self.obj = function(self.path) return self.obj @retry def xsend(self, cmd, path=None, type_by= 'xpath'): element = self.xfind(path, type_by) element.send_keys(cmd) #time.sleep(1) @retry def xclick( self, xpath=None, type_by='xpath'): element = self.xfind(xpath, type_by) element.click() self.sleep(1) @retry def xclear( self, xpath=None, type_by='xpath'): element = self.xfind(xpath, type_by) element.clear() #time.sleep(1) @retry def xrefill(self, data, xpath, type_by = 'xpath'): element = self.xfind(xpath, type_by) element.clear() element.send_keys(data) @retry def xselect(self, value, xpath=None, type_by='xpath'): self.obj = Select(self.xfind(xpath, type_by)) self.obj.select_by_visible_text(value) self.sleep(1) @retry def xget(self,url=None): if url is not None: self.curr_url = url self.driver.get(self.curr_url) self.sleep(1) @retry def have_text(self, exp_txt, path, type_by = 'xpath'): try: elem = self.xfind(path, type_by) if elem.text.find(exp_txt)!=-1: return True else: return False except Exception as e: return False def closeSession(self): super(webgui,self).closeSession() self.quit() def xcheck(self, xpath=None, type_by='xpath'): self.obj = self.xfind(xpath, type_by) if not self.obj.is_selected(): self.obj.click() self.sleep(1) def xuncheck(self, xpath=None, type_by='xpath'): self.obj = self.xfind(xpath, type_by) if self.obj.is_selected(): self.obj.click() self.sleep(1) def xswitch_2_pop(self,): browser = self.driver parent_h = browser.current_window_handle # click on the link that opens a new window handles = browser.window_handles # before the pop-up window closes handles.remove(parent_h) browser.switch_to.window(handles.pop()) # do stuff in the popup # popup window closes browser.switch_to.window(parent_h)
time.sleep(2) # 시/도 선택 :: 'Select'를 활용한 드롭다운 메뉴 선택 ele = Select(driver.find_element_by_id("sidolabel")) ele.select_by_index(8) # 학교명 검색 :: 'Select'를 활용한 드롭다운 메뉴 선택 ele = Select(driver.find_element_by_id("crseScCode")) ele.select_by_index(2) # 학교명 입력 ele = driver.find_element_by_id('orgname') ele.send_keys(student["school"]) ele = driver.find_element_by_class_name("searchBtn") ele.click() time.sleep(1) # 학교명 선택(처음에는 나타나지 않음) ele = driver.find_element_by_tag_name("em") ele.click() time.sleep(1) # 학교선택 정보 최종 제출 ele = driver.find_element_by_class_name("layerFullBtn") ele.click() time.sleep(2) ############################################################### ############# 페이지(2) : 학생 정보 입력 ###################### ###############################################################
def fill_filter_old(self, gender = None, from_age = None, till_age = None, location = None, on_site = None, walk_plan = None, url = None): self.driver.set_page_load_timeout(50) try: self.driver.get(url) #w = self.driver.get_window_size()['width'] #self.driver.set_window_size(w, 640) except: r = 1 sex_tag = 'span' # изменение от 15.12.2016 sex_tag = 'div' # переход в начало страницы self.driver.execute_script("window.scrollTo(0, 20);") sleep(3) flts = self.driver.find_elements_by_class_name("gs_filter_list") if gender is not None: lst = flts[0].find_elements_by_tag_name('li') if gender == 'm': lst[1].find_element_by_tag_name(sex_tag).click() if gender == 'f': lst[2].find_element_by_tag_name(sex_tag).click() if from_age is not None: elem = Select(flts[1].find_elements_by_tag_name('select')[0]) elem.select_by_value(from_age) #elem = flts[1].find_elements_by_tag_name('select')[0].find_element_by_xpath("//option[@value='"+from_age+"']") #elem.click() if till_age is not None: elem = Select(flts[1].find_elements_by_tag_name('select')[1]) elem.select_by_value(till_age) #elem = elem.find_element_by_xpath("option[@value='" + till_age + "']") #elem.click() if location is not None: i = 0 while i < 3: try: # до 15.12.2016 был тэг спан elem = flts[2].find_element_by_xpath("li/div[@data-field_location='" + location + "' and @data-field_country='10414533690']") self.center_click(elem) break except: self.driver.execute_script("window.scrollTo(0, 20);") i += 1 if i >= 3: # до 15.12.2016 был тэг спан elem = flts[2].find_element_by_xpath("li/div[@data-field_location='" + location + "' and @data-field_country='10414533690']") elem.click() if on_site is not None: wait = WebDriverWait(self.driver, 50) #elem = wait.until(EC.element_to_be_clickable((By.ID, 'field_onSite'))) elem = flts[9].find_element_by_id('field_onSite') elem_m = flts[9].find_element_by_id('field_refs') #elem = WebDriverWait(self.driver, 60).until((EC.visibility_of_element_located(By.ID, 'field_onSite'))) #elem = wait.until(EC.element_to_be_clickable((By.ID, 'field_onSite'))) elem = wait.until(EC.visibility_of_element_located((By.ID, 'field_onSite'))) if on_site != elem.is_selected(): #action = ActionChains(self.driver) #action.move_to_element(elem_m) #action.click(elem) #action.perform() #elem = wait.until(EC.element_to_be_clickable((By.ID, 'field_onSite'))) elem.click() #wait.until(stalenessOf(load)); #self.driver.move_to_element(elem) #print elem.get_attribute('outerHTML') #if on_site != elem.is_selected(): # elem.click() #self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") sleep(5) self.logger.write_log(WALKER_FIENDS, 0, self.logger.dumps( {'gender': gender, 'from_age': from_age, 'till_age': till_age, 'location': location, 'on_site': on_site, 'walk_plan': walk_plan}), '')
time.sleep(8) html = driver.page_source parser = MyHTMLParser() parser.feed(html) driver.quit() driver = webdriver.Chrome("chromedriver.exe") driver.get("http://taqm.epa.gov.tw/pm25/tw/HourlyData.aspx") ctlb = ["150", "33"] for i in range(len(ctlb)): elem_sites = driver.find_element_by_id("ctl14_txtDateS") elem_sites.clear() elem_sites.send_keys(t) elem_sites = driver.find_element_by_xpath( "//*[@id='ui-datepicker-div']/div[2]/button[2]") elem_sites.click() elem_sites = driver.find_element_by_id("ctl14_txtDateE") elem_sites.clear() elem_sites.send_keys(t) elem_sites = driver.find_element_by_xpath( "//*[@id='ui-datepicker-div']/div[2]/button[2]") elem_sites.click() elem_sites = Select(driver.find_element_by_id("ctl14_lbParam")) elem_sites.select_by_value(ctlb[i]) elem_sites = Select(driver.find_element_by_id("ctl14_lbSite")) elem_sites.deselect_all() for i in range(len(cts)): elem_sites.select_by_value(cts[i]) elem = driver.find_element_by_id("ctl14_btnQuery") elem.click() time.sleep(8)