def search(): try: print('正在搜索...') browser.get('https://www.taobao.com') login_button = wait.until((EC.element_to_be_clickable( (By.CSS_SELECTOR, '#J_SiteNavLogin > div.site-nav-menu-hd > div.site-nav-sign > a.h' )))) # 按住Command点击登陆按钮 actions = ActionChains(browser) actions.key_down(Keys.COMMAND).click(login_button).key_up(Keys.COMMAND) actions.perform() # 切换到新窗口扫描二维码 browser.switch_to.window(browser.window_handles[1]) # 趁这10秒,赶紧登陆验证。。 time.sleep(10) # 刷新 browser.refresh() input = wait.until( EC.presence_of_element_located((By.CSS_SELECTOR, '#q'))) input.send_keys(KEYWORD) submit = wait.until((EC.element_to_be_clickable( (By.CSS_SELECTOR, '#J_TSearchForm > div.search-button > button')))) submit.click() # 获取总页数 total = wait.until( EC.presence_of_element_located( (By.CSS_SELECTOR, '#mainsrp-pager > div > div > div > div.total'))) print(total.text) get_products() return total.text except TimeoutException: return search()
def _check_shortcuts(self): action = ActionChains(self.driver) for s in self.new_shortcuts: key_combo = self.new_shortcuts[s]['shortcut'] action.key_down( key_combo[0] ).key_down( key_combo[1] ).key_down( key_combo[2] ).key_up( key_combo[0] ).key_up( key_combo[1] ).perform() print("Executing shortcut: " + self.new_shortcuts[s]['locator'] + "...", file=sys.stderr, end="") self.wait.until( EC.presence_of_element_located( (By.XPATH, "//li[contains(@id, " + s + ") and contains(@class, 'show')]") ) ) is_open = 'show' in self.page.find_by_id(s).get_attribute('class') assert is_open is True, "Keyboard shortcut change is unsuccessful." print("OK", file=sys.stderr)
def createRoom(): driver = webdriver.Edge("E:\msedgedriver.exe") action = ActionChains(driver) driver.set_window_size(2000, 694) driver.implicitly_wait(10) driver.get("https://binarysearch.com/") driver.find_element_by_xpath( '//button[@class="Button_container__2cIrd Button_secondary__PUVBB Button_compact__3kdU9"]' ).click() driver.implicitly_wait(10) driver.find_element_by_xpath("//input[@name='usernameOrEmail']").send_keys( username) driver.implicitly_wait(10) driver.find_element_by_xpath("//input[@name='password']").send_keys( my_secret) driver.implicitly_wait(10) action.key_down(Keys.ENTER).key_up(Keys.ENTER).perform() element = WebDriverWait(driver, 10,)\ .until(EC.presence_of_element_located(((By.XPATH, "//div[@class='LobbyUsers_create-room-button__3G6v4']")))) ActionChains(driver).move_to_element(element).click().perform() driver.implicitly_wait(10) driver.find_element_by_xpath( '//form/div[3]/div[2]/div[2]/div/button').click() WebDriverWait(driver, 20).until(EC.url_contains("room")) ROOMURL = driver.current_url driver.quit() return ROOMURL
def item_link_click(context): actions = ActionChains(context.driver) item_link = context.driver.find_element(*ITEM_LOCATOR) actions.key_down(Keys.COMMAND).click(item_link).key_up( Keys.COMMAND).perform() sleep(2)
def change_name(self, name): wait_for_element_by_selector(self.driver, self.NAME_EDIT).click() actionChains = ActionChains(self.driver) actionChains.key_down(Keys.CONTROL).send_keys('a').key_up( Keys.CONTROL).key_down(Keys.BACKSPACE).key_up( Keys.BACKSPACE).perform() actionChains.send_keys(name + Keys.ENTER).perform()
def _update_json_cell(self, cell_el, value): platform = 'mac' if "platform" in self.driver.capabilities: platform = (self.driver.capabilities["platform"]).lower() elif "platformName" in self.driver.capabilities: platform = (self.driver.capabilities["platformName"]).lower() if 'mac' in platform: key_to_press = Keys.COMMAND else: key_to_press = Keys.CONTROL try: WebDriverWait(self.driver, 3).until( EC.visibility_of_element_located( (By.CSS_SELECTOR, QueryToolLocators.json_editor_text_area_css))) actions = ActionChains(self.driver) actions.key_down(key_to_press).send_keys('a').\ key_up(key_to_press).send_keys(Keys.DELETE).perform() actions.send_keys(value).perform() # Click on editor's Save button self.page.find_by_css_selector( QueryToolLocators.text_editor_ok_btn_css).click() return True except Exception: traceback.print_exc() print('Exception occurred while updating json cell ', file=sys.stderr) return False
def tweet(self, string, hashtag): for i in range(5): try: text_area = self.driver.find_element_by_class_name( "public-DraftEditor-content") except: sleep(2) try: text_area.clear() except: exit( "[-] Couldn't find text_area ! Your internet may be slow or you interacted with the browser." ) text_area.send_keys(string) text_area.send_keys(Keys.RETURN) text_area.send_keys(hashtag + " ") sleep(1) action = ActionChains(self.driver) action.key_down(Keys.CONTROL).send_keys(Keys.RETURN).key_up( Keys.CONTROL).perform()
def open_a(): baidu=driver.find_element_by_partial_link_text("度娘") jd=driver.find_element_by_partial_link_text("京东") dd=driver.find_element_by_partial_link_text("当当") d = ActionChains(driver) d.key_down(Keys.CONTROL).click(baidu).click(jd).click(dd).key_up(Keys.CONTROL).perform() sleep(5)
def get_bill_details(self, bill_row: BillSummaryRow): """Click on the 'details' link for a given bill summary, and scrape the resulting page""" with IFrameSwitch(self.driver, "mainFrame"): # We open the page in a new window by shift-clicking. actions = ActionChains(self.driver) actions.move_to_element(bill_row.detail_link) actions.key_down(Keys.SHIFT) actions.click(bill_row.detail_link) actions.key_up(Keys.SHIFT) actions.perform() self.driver.wait().until(window_count_equals(2)) other_window = self.driver.window_handles[1] detail_raw = {} with WindowSwitch(self.driver, other_window, close=True): WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.XPATH, "//table"))) table = self.driver.find_element_by_tag_name("table") for row in table.find_elements_by_tag_name("tr"): cells = row.find_elements_by_tag_name("td") if len(cells) >= 2: row_label = cells[0].text.strip() detail_raw[row_label] = cells[1].text.strip() return BillDetail( account=str(detail_raw["Account"]), rate=str(detail_raw["Rate"]), bill_start=parse_date(detail_raw["Bill Start"]).date(), bill_stop=parse_date(detail_raw["Bill Stop"]).date(), total_kwh=self.parse_float(detail_raw["Total kWh"]), on_peak_kw=self.parse_float(detail_raw["On Peak KW"]), cost=self.parse_cost(detail_raw["Total Bill"]), )
def select_month(self, month): print(month) self.find_element(*self.locator.MONTH).click() time.sleep(2) action = ActionChains(self.driver) action.key_down(Keys.ARROW_DOWN).key_up(Keys.ARROW_DOWN).send_keys( Keys.ENTER).perform()
def test_group(graph_cases): """ :type graph_cases: qmxgraph.tests.conftest.GraphCaseFactory """ graph = graph_cases('2v') actions = ActionChains(graph.selenium) actions.key_down(Keys.CONTROL) actions.perform() vertex_foo, vertex_bar = graph.get_vertices() graph.select_vertex(vertex_foo) graph.select_vertex(vertex_bar) actions = ActionChains(graph.selenium) actions.key_up(Keys.CONTROL) actions.perform() # Group selected vertices graph.selenium.execute_script("api.group()") group_fill = graph.host.styles['group']['fill_color'] group_selector = 'g>g>rect[fill="{}"]'.format(group_fill) group = graph.selenium.find_elements_by_css_selector(group_selector) assert len(group) == 1 # Ungroup selected vertices graph.selenium.execute_script("api.ungroup()") group = graph.selenium.find_elements_by_css_selector(group_selector) assert not group
def press_control_and_click_element(self, locator): if locator.startswith("xpath="): web_element = self._current_browser().find_element( By.XPATH, locator[len("xpath="):]) actions = ActionChains(self._current_browser()) actions.key_down(Keys.CONTROL).click(web_element).key_up( Keys.CONTROL).perform()
def scroll(self, key='end', loc=None, ele=None, strict=False, position=None, action='click'): key_select = ['end', 'home', 'page_up', 'page_down'] if key not in key_select: LOG_ERROR('参数key: {}输入错误, 可选有效参数为: {}'.format(key, key_select)) key_map = { 'end': Keys.END, 'home': Keys.HOME, 'page_up': Keys.PAGE_UP, 'page_down': Keys.PAGE_DOWN } if loc or ele: self.move_to_element_and_click(loc=loc, ele=ele, strict=strict, action=action) elif position: self.move_by_offset_and_click(xoffset=position[0], yoffset=position[1], action=action) else: actions = ActionChains(self.driver) if action == 'click': actions.click() elif action == 'double_click': actions.double_click() elif action == 'context_click': actions.context_click() else: pass actions.perform() actions = ActionChains(self.driver) actions.key_down(key_map[key]) actions.key_up(key_map[key]) actions.perform()
def main(): chrome_options = Options() # chrome_options.add_experimental_option("debuggerAddress", '127.0.0.1:9515') chrome_driver = 'C:\Program Files\Google\Chrome\Application\chromedriver' # chromedriver的文件位置 b = webdriver.Chrome(executable_path=chrome_driver, options=chrome_options) b.get('https://www.mihuashi.com/artworks') # 设置浏览器的大小 b.set_window_size(1000, 1000) # 显示等待 waiter = WebDriverWait(b, 3, poll_frequency=0.1, ignored_exceptions=None) # 创建 Beautiful Soup 对象 html = BeautifulSoup(b.page_source, "lxml") # 格式化输出 soup 对象的内容 print(html.prettify) builder = ActionChains(b) while True: try: images = b.find_elements_by_class_name('artwork-cell__image') for image in images: download_image = image with open( 'C:\\Users\\Administrator\\Downloads\\插图\\' + download_image.id + '.png', 'wb') as f: f.write( base64.b64decode(download_image.screenshot_as_base64)) f.close() builder.key_down(Keys.ESCAPE).perform() time.sleep(1) except TimeoutException: alert(b, "页面元素读取超时") time.sleep(3) alert_accept(b) finally: # 休眠一下 time.sleep(1)
def keyboard_functionality_check(): results = {"enter": False, "copy": False} action = ActionChains(driver) #Keyboard actions #Submit with Enter key test driver.get(url_path + login_route) driver.find_element_by_id("email").send_keys(registered_emails[0]) driver.find_element_by_id("pass").send_keys(registered_passwords[0]) driver.find_element_by_id("pass").send_keys(Keys.ENTER) results["enter"] = assertCheck( "Submit with enter key test %d:" % (1), driver.find_element_by_tag_name("h1").get_attribute('innerHTML'), "Login Successful. Welcome " + registered_emails[0]) #Copy, paste and select all keyboard shortcuts test (Ctrl + C, Ctrl + V, Ctrl + A) driver.get(url_path + login_route) driver.find_element_by_id("passhideBtn").click() driver.find_element_by_id("pass").send_keys(registered_passwords[0]) action.key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform() action.key_down(Keys.CONTROL).send_keys("c").key_up(Keys.CONTROL).perform() driver.find_element_by_id("email").click() action.key_down(Keys.CONTROL).send_keys("v").key_up(Keys.CONTROL).perform() results["copy"] = assertCheck( "Copy, paste and select all keyboard shortcuts test %d:" % (1), driver.find_element_by_id("email").get_attribute('value'), registered_passwords[0]) return results
class baseClass(): def feach_browser(self): self.driver = webdriver.Chrome(executable_path=r"C:\Users\sony\PycharmProjects\SeleniumTestProj\Drivers\chromedriver.exe") return self.driver def feach_url(self,url): self.driver.get(url) def current_url(self): c_url=self.driver.current_url return c_url def url_title(self): url_title=self.driver.title return url_title def insert_value(self,w_element,value): w_element.send_keys(value) def we_click(self,w_element): w_element.click() def mouseOver(self,w_element): self.ac = ActionChains(self.driver) self.ac.move_to_element(w_element).perform() def click(self): self.ac.click().perform() def r_click(self,w_element): self.ac.context_click(w_element).perform() def double_click(self,w_element): self.ac.double_click(w_element).perform() def print_capital(self,key_name,input_txt): self.ac.key_down(Keys.SHIFT, key_name).send_keys(input_txt).key_up(Keys.SHIFT, key_name).perform() def drag_and_drop(self,src,dest): self.ac.drag_and_drop(src,dest).perform() def click_and_hold(self,src,dest): self.ac.click_and_hold(src).release(dest) def switch_to_alert(self): self.alerts=self.driver.switch_to.alert def switch_to_frame(self,frame_id): self.frames=self.driver.switch_to.frame(frame_id) def switch_to_window(self,win_id): self.windows=self.driver.switch_to.window(win_id) def switch_to_parent(self): self.driver.switch_to.default_content() def alert_accept(self): self.alerts.accept() def alert_dismiss(self): self.alerts.dismiss() def send_text_to_alert(self,alert_text): self.alerts.send_keys(alert_text) def get_text_frm_alert(self): alrt_txt=self.alerts.text return alrt_txt def current_window(self): par_id=self.driver.current_window_handle return par_id def all_open_windows(self): all_id=self.driver.window_handles return all_id def close_current_window(self): self.driver.close() def close_all_driver_win(self): self.driver.quit() def sleep_mtd(self,sec): time.sleep(sec)
def _get_item_code(self): browser = super()._get_item_code() time.sleep(10) browser.get(self.url) try: myElem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, self.SEARCH_TAB))) except TimeoutException: print ("Loading took too much time!") elem = browser.find_element_by_xpath(self.ITEM_CODE_TAGS['refresh']) elem.click() actions = ActionChains(browser) actions.key_down(Keys.CONTROL).key_down(Keys.TAB).key_up(Keys.TAB).key_up(Keys.CONTROL).perform() # looks like something is wrong with this site # lets try with scrolling first and scraping second # I think they are trying to prevent scraping by bots # if they dont see anyhuman like interaction # they are freezing dom browser.execute_script("window.scrollTo(0, 2900)") time.sleep(10) for elem in browser.find_elements_by_xpath(f'//{self.ITEM_CODE_TAGS["element"]}'): result_ = self._check_element_tags(self.ITEM_CODE_TAGS["tags"], elem) if result_: code_ = elem.get_attribute(self.ITEM_CODE_TAGS["value"]) product = re.compile(f"^{self.ITEM_PAGE}.*$").match(code_) if product is not None: yield code_.split('?')[0] browser.close()
class TextEditorHelper: def __init__(self, driver): self.driver = driver self.environmentSelectorDropdownItem = self.driver.find_element_by_xpath( ".//span[contains(text(),'Python 2.7')]") self.actions = ActionChains(self.driver) def scrollIntoView(self): self.driver.execute_script( "arguments[0].scrollIntoView();", self.driver.find_element_by_id("codeSection")) def moveToTextEditor(self): self.actions.move_to_element_with_offset( self.environmentSelectorDropdownItem, 0, 200) self.actions.click() self.actions.perform() def deleteCode(self): self.actions.key_down(Keys.LEFT_CONTROL).send_keys('a').key_up( Keys.LEFT_CONTROL).perform() self.actions.send_keys(Keys.DELETE).perform() def addCode(self, code): self.actions.send_keys(code) self.actions.perform()
def start_requests(self): self.driver = webdriver.Chrome(os.getcwd() + "\\chromedriver.exe") self.driver.get( 'https://publicaccess.wycombe.gov.uk/idoxpa-web/search.do?action=advanced' ) self.driver.find_element_by_id('applicationValidatedStart').send_keys( '01/12/2020') self.driver.find_element_by_id('applicationValidatedEnd').send_keys( '14/12/2020') self.driver.find_element_by_xpath( '//*[@id="advancedSearchForm"]/div[4]/input[2]').click() time.sleep(5) self.driver.execute_script( "arguments[0].scrollIntoView();", self.driver.find_element_by_id('searchresults')) # sub_driver = self.driver.find_element_by_id('searchresults').find_elements_by_tag_name('li') # sub_driver[0].find_element_by_tag_name('a').click() # while True: # actions = ActionChains(browser) for i in self.driver.find_elements_by_xpath( "// *[ @ id = 'searchresults'] / li / a"): actions = "" actions = ActionChains(self.driver) actions.key_down(Keys.CONTROL).click(i).key_up( Keys.CONTROL).perform() # i.send_keys(Keys.CONTROL + 't').click() self.driver.switch_to.window(self.driver.window_handles[1]) time.sleep(5) new_url = '' new_url = self.driver.current_url print('current url is: ' + new_url) yield SeleniumRequest(url=new_url, callback=self.parse) # data_of_proposal = self.driver.find_element_by_xpath("//*[@id='simpleDetailsTable']/tbody/tr[6]/td").text # print(data_of_proposal) self.driver.close() self.driver.switch_to.window(self.driver.window_handles[0]) try: self.driver.find_element_by_link_text('Next').click() # url = browser.find('a', {'class': 'next'}).text # if url=='Next': # browser. # Next_url="https://publicaccess.wycombe.gov.uk"+str(soup.find('a', {'class': 'next'}).get('href')) # print(Next_url) # return Next_url except: print("No Page left to proceed") break # if not url: # break # print(url) self.driver.close()
def step_alt_click(self, locators, n=1): """ Method to start editing of test case step or 'nth' step (ALT+MB1 click on step)""" try: chain = ActionChains(self.browser) elements = self.find_elements(locators) chain.key_down(Keys.ALT).click(elements[n-1]).key_up(Keys.ALT).perform() except Exception as e: print(f"Locators {locators} in 'step_alt_click' - An Exception occurred:", e)
def change_description(self, description): wait_for_element_by_selector(self.driver, self.DESCRIPTION_EDIT).click() actionChains = ActionChains(self.driver) actionChains.key_down(Keys.CONTROL).send_keys('a').key_up( Keys.CONTROL).key_down(Keys.BACKSPACE).key_up( Keys.BACKSPACE).perform() actionChains.send_keys(description + Keys.ENTER).perform()
def input_text_in_search(self, word): with allure.step(f'Вводим в поле поска слово "{word}"'): self.find_element(self.driver, self.search_button).click() self.find_element(self.driver, self.search_form_field).send_keys(word) action = ActionChains(self.driver) action.key_down(Keys.ENTER).perform() self.logger.info(f'Ищем слово {word}')
def command_ctrl_with_click(browser, col_name, command_or_ctrl): chains = ActionChains(browser) element = browser.execute_script( "return $('.ember-table-header-container .ember-table-content:contains(" + col_name + ")').parent().parent()") if command_or_ctrl == "command": chains.key_down(Keys.COMMAND).click(element[0]).key_up(Keys.COMMAND).perform() elif command_or_ctrl == "control": chains.key_down(Keys.CONTROL).click(element[0]).key_up(Keys.COMMAND).perform()
def mouse_over_with_control(locator, x_wiggle=0): sl: SeleniumLibrary = BuiltIn().get_library_instance("SeleniumLibrary") action_chains = ActionChains(sl.driver) action_chains.key_down(Keys.CONTROL) action_chains.move_to_element(sl.find_element(locator)) wiggle(action_chains, x_wiggle) action_chains.key_up(Keys.CONTROL) return action_chains.perform()
def boxi_overtime_extract(): boxi_iframe_switch() actionChains = ActionChains(browser) actionChains.double_click( browser.find_element_by_id('ListingURE_listColumn_4_0_1')).perform() try: WebDriverWait(browser, 10).until( ec.frame_to_be_available_and_switch_to_it('webiViewFrame')) except TimeoutException: print("Loading took too much time!") browser.find_element_by_xpath('//*[@id="IconImg_Txt_refresh"]').click() try: WebDriverWait(browser, 10).until( ec.presence_of_element_located((By.XPATH, '// *[ @ id = "PV1"]'))) except TimeoutException: print("Loading took too much time!") dateinput = browser.find_element_by_id('LPV1_textField') firstelem = browser.find_element_by_xpath( '//*[@id="mlst_bodyPV1List"]/div/table/tbody/tr[1]/td/div') secondelem = browser.find_element_by_xpath( '//*[@id="mlst_bodyPV1List"]/div/table/tbody/tr[5]/td/div') actionChains = ActionChains(browser) actionChains.key_down( Keys.SHIFT).click(firstelem).click(secondelem).key_up( Keys.SHIFT).perform() browser.find_element_by_xpath('//*[@id="theBttnIconPV1DelButton"]').click() for i in finweeks: dateinput.clear() dateinput.send_keys(i) browser.find_element_by_id("theBttnIconPV1AddButton").click() dateinput.clear() dateinput.send_keys(finmonth) browser.find_element_by_id("theBttnIconPV1AddButton").click() browser.find_element_by_id("theBttnCenterImgpromptsOKButton").click() try: WebDriverWait(browser, 250).until( ec.presence_of_element_located( (By.XPATH, '//*[@id="IconImg_iconMenu_arrow_docMenu"]'))) except TimeoutException: print("Loading took too much time!") browser.find_element_by_xpath( '//*[@id="IconImg_iconMenu_arrow_docMenu"]').click() hov = browser.find_element_by_id( 'iconMenu_menu_docMenu_span_text_saveReportComputerAs') ActionChains(browser).move_to_element(hov).perform() time.sleep(1) browser.find_element_by_id( 'saveReportComputerAs_span_text_saveReportXLS').click() print(path + 'WSTATS_OVERTIME_EXTRACT' + '.xls') while not os.path.exists(path + 'WSTATS_OVERTIME_EXTRACT.xls'): time.sleep(1) browser.get('https://bo-wf.scot.nhs.uk/InfoViewApp/listing/main.do') browser.switch_to.alert.accept() print("Boxi Overtime Extract - Complete")
def switch_tab(self, browser_instance=None, tab_number=None, browser_type="firefox"): """Switching to different tabs in a browser with unique tab_number""" status = True if browser_instance is None: browser_instance = self.current_browser if tab_number is not None: try: tab_number = int(tab_number) except: print_error("{0} is not a valid tab number".format(tab_number)) status = False else: if tab_number > len(browser_instance.window_handles) or tab_number < 1: print_error("{0} is not a valid tab number".format(tab_number)) status = False else: tab_number -= 1 current_tab = 0 current_window_handle = browser_instance.current_window_handle for i in range(0, len(browser_instance.window_handles)): if browser_instance.window_handles[i] == current_window_handle: current_tab = i break if tab_number != current_tab: if current_tab < tab_number: times = tab_number - current_tab else: times = len(browser_instance.window_handles) - current_tab times += tab_number if browser_type == "firefox": action_chains = ActionChains(browser_instance) action_chains.key_down(Keys.ALT) for i in range(0, times): action_chains.send_keys('`') action_chains.perform() else: element = browser_instance.find_element_by_tag_name('body') for i in range(0, times): element.send_keys(Keys.LEFT_CONTROL, Keys.TAB) browser_instance.switch_to.window(browser_instance.window_handles[tab_number]) else: current_tab = 0 current_window_handle = browser_instance.current_window_handle for i in range(0, len(browser_instance.window_handles)): if browser_instance.window_handles[i] == current_window_handle: current_tab = i tab_number = current_tab + 1 if tab_number >= len(browser_instance.window_handles): tab_number = 0 if browser_type == "firefox": browser_instance.find_element_by_tag_name('body').send_keys(Keys.LEFT_ALT, '`') else: browser_instance.find_element_by_tag_name('body').send_keys(Keys.LEFT_CONTROL, Keys.TAB) browser_instance.switch_to.window(browser_instance.window_handles[tab_number]) return status
def click_multiple_with_ctrl_down(self, locator, numbers=5): elements = self._element_find(locator, False, True) actions = ActionChains(self._current_browser()) actions.key_down(keys.Keys.CONTROL).perform() sampl = random.sample(elements, int(numbers)) for e in sampl: e.click() actions.key_up(keys.Keys.CONTROL).perform()
def click_multiple_with_ctrl_down(self, locator,numbers=5): elements = self._element_find(locator, False, True) actions = ActionChains(self._current_browser()) actions.key_down(keys.Keys.CONTROL).perform() sampl = random.sample(elements,int(numbers)) for e in sampl: e.click() actions.key_up(keys.Keys.CONTROL).perform()
def open_a(): baidu = driver.find_element_by_partial_link_text("度娘") dangdang = driver.find_elements_by_partial_link_text("当当") jingdong = driver.find_element_by_partial_link_text("京东") b = ActionChains(driver) b.key_down( Keys.CONTROL).click(baidu).click(dangdang).click(jingdong).key_up( Keys.CONTROL).perform() sleep(2)
def zoom_selection(self): center = self.driver.execute_script(GetScripts.getContainerCenter) actions = ActionChains(self.driver) actions.move_to_element_with_offset(self.element, int(center['x']), int(center['y'])) actions.key_down(Keys.SHIFT) actions.click_and_hold() actions.move_by_offset(300, 300) actions.release() actions.perform()
def test_action_chains_keys(self): self.driver.get("http://sahitest.com/demo/label.htm") element = self.driver.find_element(By.XPATH, '/html/body/label[1]/input') action = ActionChains(self.driver) action.key_down(Keys.CONTROL).send_keys("aaaaa").key_up(Keys.CONTROL) action.send_keys(Keys.BACK_SPACE) action.perform() print(element.get_attribute("value"))
def close_tab(self, browser_instance=None, tab_number=None, browser_type="firefox"): """Closing tabs in a browser with unique tab_number""" if browser_instance is None: browser_instance = self.current_browser if len(browser_instance.window_handles) > 1: prior_current_tab = False current_window_handler = browser_instance.current_window_handle for i in range(0, len(browser_instance.window_handles)): if browser_instance.window_handles[i] == current_window_handler: prior_current_tab = i status = True if tab_number is not None: status = self.switch_tab(browser_instance, tab_number, browser_type) if status: tab_number = int(tab_number) - 1 browser_instance.find_element_by_tag_name('body').send_keys(Keys.LEFT_CONTROL, 'w') sleep(2) if tab_number == len(browser_instance.window_handles): tab_number -= 1 browser_instance.switch_to.window(browser_instance.window_handles[tab_number]) if prior_current_tab == len(browser_instance.window_handles): prior_current_tab -= 1 if prior_current_tab != tab_number: if tab_number < prior_current_tab: times = prior_current_tab - tab_number else: times = len(browser_instance.window_handles) - tab_number times += prior_current_tab if browser_type == "firefox": action_chains = ActionChains(browser_instance) action_chains.key_down(Keys.ALT) for i in range(0, times): action_chains.send_keys('`') action_chains.perform() else: element = browser_instance.find_element_by_tag_name('body') for i in range(0, times): element.send_keys(Keys.LEFT_CONTROL, Keys.TAB) browser_instance.switch_to.window(browser_instance.window_handles[prior_current_tab]) else: if browser_type == "firefox": print_info("The tab_number argument is None. Current window will be closed") else: print_info("The tab_number argument is None. Current tab will be closed") browser_instance.find_element_by_tag_name('body').send_keys(Keys.LEFT_CONTROL, 'w') if prior_current_tab == len(browser_instance.window_handles): prior_current_tab = 0 browser_instance.switch_to.window(browser_instance.window_handles[prior_current_tab]) else: status = self.close_browser(browser_instance) return status
def clickAndClearWindowTextView(window): print "clickAndClearWindowTextView: " + window.get_attribute("AXTitle") action = ActionChains(driver).click(window) action.key_down(Keys.COMMAND).send_keys("a").key_up( Keys.COMMAND).send_keys(Keys.BACKSPACE).perform() textView = utilities.findElementByXPath( driver, "/AXApplication/AXWindow[0]/AXScrollArea[0]/AXTextArea[@AXIdentifier='First Text View']" ) return textView
def test_report(self): self.browser.get(self.live_server_url + '/') # Login username = self.browser.find_element_by_id('username') username.send_keys('Jim') password = self.browser.find_element_by_id('password') # Send the wrong password password.send_keys('correcthorsebatterystaple') # Submit the form submit = self.browser.find_element_by_id('submit') submit.click() # Navigate to the sale page img = self.browser.find_element_by_xpath( '//div[@class="card small grey darken-3"][1]//img[@id="report-image"]') img.click() # Get the choose showing modal showing = self.browser.find_element_by_xpath( '//div[@class="col s6 center-align"][1]/button') showing.click() wait = WebDriverWait(self.browser, 10) element = wait.until(EC.element_to_be_clickable((By.ID, 'picker-modal'))) modal = self.browser.find_element_by_id('picker-modal') self.assertTrue(modal.is_displayed()) occ = self.browser.find_element_by_id('showing') occ.click() free_text = self.browser.find_element_by_xpath('//div[@id="sale-update"]//p').text self.assertIn('No tickets sold', free_text) self.assertIn('No tickets reserved', free_text) self.assertIn('80 tickets left', free_text) # Check selling tickets adds up properly pricing = models.InHousePricing.objects.get(id=1) member_price = pricing.member_price concession_price = pricing.concession_price public_price = pricing.public_price mat_f_price = pricing.matinee_freshers_price mat_f_nnt_price = pricing.matinee_freshers_nnt_price out = self.browser.find_element_by_id('out1').text member = self.browser.find_element_by_id('member') action = ActionChains(self.browser) action.click(on_element=member) action.send_keys('1') action.key_down(Keys.CONTROL) action.key_up(Keys.CONTROL) action.perform()
def delete_files(self, file_paths): """ Delete all the files in the list `file_paths` """ # need select all the files given in file_paths self('files_tab').click() for filename in file_paths: element = self.find_file(filename) chain = ActionChains(self.browser) #FIXME: Mac OSX does not use CONTROL key chain.key_down(Keys.CONTROL).click(element).key_up(Keys.CONTROL).perform() self('files_tab').click() self('file_menu').click() self('delete_files_button').click()
def test_remove_success(self): table = self.driver.find_element_by_id('dataTable') self.create_units(table) tr = table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(3) + ')') actions = ActionChains(self.driver) actions.move_to_element(tr.find_element_by_css_selector('td:nth-child(2)')) actions.click() actions.key_down(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(5) + ') td:nth-child(3)')) actions.click() actions.key_up(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(4) + ') td:nth-child(3)')) actions.context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN) actions.send_keys(Keys.RETURN) actions.perform() self.assertEqual(len(self.driver.find_elements_by_css_selector('.htCore tbody tr')), 3 * 2)
def interact_mouse( self ): ''' Perform some mouse interaction in the current active browser window. ''' canvas = self.__browser.find_element_by_tag_name( 'canvas' ) canvas_width = canvas.get_attribute('width') canvas_height = canvas.get_attribute('height') # move to canvas center to trigger a caption actions = ActionChains( self.__browser ) actions.click( canvas ) actions.move_to_element_with_offset( canvas, int(canvas_width)/2, int(canvas_height)/2 ) actions.perform() time.sleep(3) # # rotate, pan, zoom # actions = ActionChains( self.__browser ) actions.click( canvas ) # rotate for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 10, 0 ); actions.release( canvas ) for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, -10 ); actions.release( canvas ) # zoom (not possible right now since the scrollwheel can't be triggered) # pan for i in range( 10 ): actions.key_down( Keys.LEFT_SHIFT ) actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, 10 ); actions.release( canvas ) actions.perform()
def test_remove_permission(self): table = self.driver.find_element_by_id('dataTable') self.create_units(table) self.driver.authorize(username=self.guest.email, password='******') self.driver.open_url(reverse('units:list', kwargs={'lab_pk': unicode(self.lab.pk)})) table = self.driver.find_element_by_id('dataTable') tr = table.find_element_by_css_selector('.htCore tbody tr:nth-child(1)') actions = ActionChains(self.driver) actions.move_to_element(tr.find_element_by_css_selector('td:nth-child(2)')) actions.click() actions.key_down(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(5) + ') td:nth-child(3)')) actions.click() actions.key_up(Keys.SHIFT) actions.move_to_element(table.find_element_by_css_selector('.htCore tbody tr:nth-child(' + str(4) + ') td:nth-child(3)')) actions.context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN) actions.send_keys(Keys.RETURN) actions.perform() self.assertTrue(self.driver.is_element_present('.alert-danger')) self.assertEqual(self.driver.find_element_by_css_selector('.messages').text, 'PERMISSION DENIED')
def delete_files(self, file_paths, confirm=True): """ Delete all the files in the list `file_paths` """ # need select all the files given in file_paths self('files_tab').click() for filename in file_paths: element = self.find_file(filename) chain = ActionChains(self.browser) #Mac OSX does not use CONTROL key if sys.platform == 'darwin': chain.key_down(Keys.SHIFT).click(element).key_up(Keys.SHIFT).perform() else: chain.key_down(Keys.CONTROL).click(element).key_up(Keys.CONTROL).perform() self('files_tab').click() self('file_menu').click() self('delete_files_button').click() page = ConfirmationPage(self) if confirm: page.click_ok() else: page.click_cancel()
def trigger_keystrokes(browser, *keys): """ Send the keys in sequence to the browser. Handles following key combinations 1. with modifiers eg. 'control-alt-a', 'shift-c' 2. just modifiers eg. 'alt', 'esc' 3. non-modifiers eg. 'abc' Modifiers : http://seleniumhq.github.io/selenium/docs/api/py/webdriver/selenium.webdriver.common.keys.html """ for each_key_combination in keys: keys = each_key_combination.split('-') if len(keys) > 1: # key has modifiers eg. control, alt, shift modifiers_keys = [getattr(Keys, x.upper()) for x in keys[:-1]] ac = ActionChains(browser) for i in modifiers_keys: ac = ac.key_down(i) ac.send_keys(keys[-1]) for i in modifiers_keys[::-1]: ac = ac.key_up(i) ac.perform() else: # single key stroke. Check if modifier eg. "up" browser.send_keys(getattr(Keys, keys[0].upper(), keys[0]))
def interact_keyboard( self ): ''' Perform some keyboard interaction in the current active browser window. ''' canvas = self.__browser.find_element_by_tag_name( 'canvas' ) actions = ActionChains( self.__browser ) actions.click( canvas ) # # keyboard events # # rotate for i in range( 30 ): actions.send_keys( Keys.ARROW_RIGHT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_UP ) for i in range( 30 ): actions.send_keys( Keys.ARROW_LEFT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_DOWN ) # zoom for i in range( 50 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_LEFT ) for i in range( 25 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_RIGHT ) # pan actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_RIGHT, Keys.ARROW_RIGHT, Keys.ARROW_RIGHT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_LEFT, Keys.ARROW_LEFT, Keys.ARROW_LEFT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_UP, Keys.ARROW_UP, Keys.ARROW_UP ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_DOWN, Keys.ARROW_DOWN ) actions.perform()
elements = driver.find_elements_by_class_name("db10ub") html_source = driver.page_source soup = BeautifulSoup(html_source) table = soup.find('table', cellpadding='3') while y < len(elements): if soup.findAll('a',href=True): for item in table: y = str(y) element = driver.find_element_by_xpath('//table[2]/tbody/tr[4]/td/div/table/tbody/tr['+y+']/td[2]/font/a') y = int(y) element.click() y+=1 print y html_source = driver.page_source soup = BeautifulSoup(html_source) if soup.find('table', id='tabTwo'): element = driver.find_element_by_xpath("//tr[2]/td[6]/font/a") element.click() sleep(5) win = driver.window_handles driver.switch_to_window(win[1]) AC.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() sleep(1) AC.send_keys(Keys.ENTER) print "Saved" driver.switch_to_window(win[0]) driver.back() z+=1 driver.back()
def runTests( xtkTestFile, xtkLibDir, browserString ): print 'RUNNING OFFSCREEN TESTING..' browser = getBrowser( xtkLibDir, browserString ) if not browser: return None if xtkTestFile.find( 'build' ) == -1: # this is against the DEV tree # start coverage server coverageServer( xtkLibDir ) browser.get( "http://localhost:8080/jscoverage.html" ) # now some selenium fun locationfield = browser.find_element_by_id( 'location' ) locationfield.clear() # fill in url actions = ActionChains( browser ) actions.click( locationfield ) actions.send_keys( 'testing/xtk_tests.html' ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.RETURN ) actions.perform() browser.switch_to_window( browser.window_handles[-1] ) #browser.switch_to_frame( browser.find_elements_by_tag_name( "iframe" )[0] ) else: # we don't need os.sep here since it's a url browser.get( "file://" + xtkTestFile ) time.sleep( 3 ) result_unit = browser.execute_script( 'return window.G_testRunner.getReport(true);' ) time.sleep( 1 ) browser.switch_to_window( browser.window_handles[0] ) #browser.close() print 'RUNNING OFFSCREEN TESTING.. DONE!' # if xtkTestFile.find( 'build' ) == -1: # this is against the DEV tree # stop coverage server #coverageServer( xtkLibDir, 'stop' ) #return result #def testVisualization( xtkLibDir, browserString, againstBuild=False ): print 'RUNNING VISUAL TESTING..' #browser = getBrowser( xtkLibDir, browserString ) if not browser: return None # list of tests tests = ['test_trk.html', 'test_vtk.html', 'test_nrrd.html', 'test_vr.html', 'test_labelmap.html', 'test_shapes.html', 'test_mgh.html', 'test_mgz.html', 'test_stl.html', 'test_binstl.html'] #testURL = "file://" + xtkLibDir + "/../testing/visualization/" testURL = "testing/visualization/" baselineDir = os.path.abspath( xtkLibDir + "/../testing/visualization/baselines/" ) # we test the visualization with a fixed window size browser.set_window_size( 800, 600 ) output = '' # loop through the tests for t in tests: # open the test url = testURL + t #if againstBuild: # url += '?build' #browser.get( testURL + t ) browser.switch_to_default_content() # now some selenium fun locationfield = browser.find_element_by_id( 'location' ) locationfield.clear() # fill in url actions = ActionChains( browser ) actions.click( locationfield ) actions.send_keys( url ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.TAB ) actions.send_keys( Keys.RETURN ) actions.perform() browser.switch_to_window( browser.window_handles[-1] ) #browser.switch_to_frame( browser.find_elements_by_tag_name( "iframe" )[0] ) # wait until loading fully completed timer = 0 while not browser.execute_script( 'return test_renderer.loadingCompleted' ) and timer < 5: time.sleep( 1 ) # loading did not complete yet timer += 1 time.sleep( 1 ) # perform interaction tests, if we are using chrome if browserString == 'chrome': canvas = browser.find_element_by_tag_name( 'canvas' ) actions = ActionChains( browser ) actions.click( canvas ) # # keyboard events # # rotate for i in range( 30 ): actions.send_keys( Keys.ARROW_RIGHT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_UP ) for i in range( 30 ): actions.send_keys( Keys.ARROW_LEFT ) for i in range( 30 ): actions.send_keys( Keys.ARROW_DOWN ) # zoom for i in range( 50 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_LEFT ) for i in range( 25 ): actions.key_down( Keys.LEFT_ALT ) actions.send_keys( Keys.ARROW_RIGHT ) # pan actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_RIGHT, Keys.ARROW_RIGHT, Keys.ARROW_RIGHT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_LEFT, Keys.ARROW_LEFT, Keys.ARROW_LEFT ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_UP, Keys.ARROW_UP, Keys.ARROW_UP ) actions.key_down( Keys.LEFT_SHIFT ) actions.send_keys( Keys.ARROW_DOWN, Keys.ARROW_DOWN ) # # mouse # actions.click( canvas ) # rotate for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 10, 0 ); actions.release( canvas ) for i in range( 30 ): actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, -10 ); actions.release( canvas ) # zoom # pan for i in range( 10 ): actions.key_down( Keys.LEFT_SHIFT ) actions.click_and_hold( None ) actions.move_to_element_with_offset( canvas, 0, 10 ); actions.release( canvas ) actions.perform() # create a screenshot and save it to a temp. file testId = os.path.splitext( t )[0] testFileId = testId + '_' + browserString tmpfile = tempfile.mkstemp( suffix='.png', prefix='xtk_' + testFileId )[1] browser.save_screenshot( tmpfile ) # baseline baseline = os.path.join( baselineDir, testFileId + '_baseline.png' ) # compare temp. file vs. baseline testPassed = compareImages( tmpfile, baseline ) _now = datetime.now() timestamp = str( _now.hour ).zfill( 2 ) + ':' + str( _now.minute ).zfill( 2 ) + ':' + str( _now.second ).zfill( 2 ) + '.' + str( _now.microsecond / 1000 ).zfill( 3 ) if testPassed: testPassed = "PASSED : " + tmpfile + " : " + baseline + " : " else: testPassed = "FAILED : " + tmpfile + " : " + baseline + " : " testPassed += "\n" + timestamp + " ERROR in Visualization" + testId + '\nComparison against baseline failed.\n' output += timestamp + " Visualization" + testId + ' : ' + testPassed + '\n' browser.switch_to_window( browser.window_handles[0] ) #browser.close() _now = datetime.now() timestamp = str( _now.hour ).zfill( 2 ) + ':' + str( _now.minute ).zfill( 2 ) + ':' + str( _now.second ).zfill( 2 ) + '.' + str( _now.microsecond / 1000 ).zfill( 3 ) result = output + timestamp + ' Done\n' print output print 'RUNNING VISUAL TESTING.. DONE!' browser.switch_to_window( browser.window_handles[0] ) browser.execute_script( 'jscoverage_storeButton_click();' ) time.sleep( 1 ) browser.execute_script( 'jscoverage_recalculateSummaryTab();' ) summaryTable = browser.execute_script( 'return document.getElementById("summaryTable").innerHTML;' ) # parse the summary table data = summaryTable.replace( '\n', '' ).split( '</tr>' ) secondLine = data[1] totalNumberOfFiles = secondLine.split( '<span>' )[1].split( '</span>' )[0] totalLines = secondLine.split( '"numeric">' )[1].split( '</td>' )[0] totalTestedLines = secondLine.split( '"numeric">' )[2].split( '</td>' )[0] totalCoverage = secondLine.split( '"pct">' )[1].split( '%' )[0] covFiles = [] for i in range( 2, len( data ) - 1 ): line = data[i] fileName = line.split( '"#">' )[1].split( '</a>' )[0] lines = int( line.split( '"numeric">' )[1].split( '</td>' )[0] ) testedLines = int( line.split( '"numeric">' )[2].split( '</td>' )[0] ) untestedLines = lines - testedLines coveragePercent = line.split( '"pct">' )[1].split( '%' )[0] covFiles.append( [fileName, lines, testedLines, untestedLines, coveragePercent] ) # create XML from socket import getfqdn # WRITE XML from xml.dom import minidom # GET DATE #from cElementTree.SimpleXMLWriter import XMLWriter import string xml = minidom.Document() system_info = os.uname() siteElement = xml.createElement( 'Site' ) systeminfo = os.uname() siteElement.setAttribute( 'BuildName', system_info[0] + '-' + system_info[2] ) hostname = getfqdn() buildtype = 'Experimental' now = datetime.now() buildtime = str( now.year ) + str( now.month ) + str( now.day ) + "-" + str( now.minute ) + str( now.second ) #buildstamp = '20120603-0100-Nightly'# + '-' + buildtype buildstamp = buildtime + '-' + buildtype siteElement.setAttribute( 'BuildStamp', buildstamp ) siteElement.setAttribute( 'Name', hostname ) siteElement.setAttribute( 'Hostname', hostname ) xml.appendChild( siteElement ) buildElement = xml.createElement( 'Coverage' ) siteElement.appendChild( buildElement ) fillxml( xml, buildElement, 'StartDateTime', time.strftime( "%b %d %H:%M %Z", time.gmtime() ) ) fillxml( xml, buildElement, 'EndDateTime', time.strftime( "%b %d %H:%M %Z", time.gmtime() ) ) for f in covFiles: fileName = f[0] lines = f[1] testedLines = f[2] untestedLines = f[3] coveragePercent = f[4] fileElement = xml.createElement( 'File' ) fileElement.setAttribute( 'Name', os.path.split( fileName )[1] ) fileElement.setAttribute( 'FullPath', fileName ) fileElement.setAttribute( 'Covered', 'true' ) buildElement.appendChild( fileElement ) fillxml( xml, fileElement, 'LOCTested', str( testedLines ) ) fillxml( xml, fileElement, 'LOCUntested', str( untestedLines ) ) fillxml( xml, fileElement, 'PercentCoverage', str( coveragePercent ) ) fillxml( xml, buildElement, 'LOCTested', str( totalTestedLines ) ) fillxml( xml, buildElement, 'LOCUntested', str( int( totalLines ) - int( totalTestedLines ) ) ) fillxml( xml, buildElement, 'LOC', str( int( totalLines ) ) ) fillxml( xml, buildElement, 'PercentCoverage', str( totalCoverage ) ) f2 = open( 'XTKCoverage.xml', 'w' ) f2.write( xml.toxml() ) f2.close() browser.quit() return [result_unit, result]
def clickAndClearWindowTextView(window): print "clickAndClearWindowTextView: " + window.get_attribute("AXTitle") action = ActionChains(driver).click(window) action.key_down(Keys.COMMAND).send_keys("a").key_up(Keys.COMMAND).send_keys(Keys.BACKSPACE).perform() textView = utilities.findElementByXPath(driver, "/AXApplication/AXWindow[0]/AXScrollArea[0]/AXTextArea[@AXIdentifier='First Text View']") return textView