def test_1486(self): """ Module登记-正确输入各个输入项 :return: """ self.driver.get('http://222.29.77.148:8205/pages/login.html') self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/input[1]').send_keys('administrator') self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/input[2]').send_keys('letmein') action = ActionChains(self.driver) action.click_and_hold(self.driver.find_element_by_xpath('//*[@id="mpanel1"]/div/div/div/i')).perform() action.move_by_offset(273, 0).perform() action.release().perform() #点击登录 self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div/div/button').click() time.sleep(3) #点击app业务管理 self.driver.find_element_by_xpath('//*[@id="seconde-header-nav"]/li[2]').click() #点击module管理 self.driver.find_element_by_xpath('//*[@id="sidebar"]/ul[2]/ul/li[1]/a/span[1]').click() #点击module登记 //*[@id="sidebar"]/ul[2]/ul/li[1]/a/span[1] self.driver.find_element_by_xpath('//*[@id="67e84f93-e164-4670-99b7-e6aa29713642"]/a').click() #切换到frame self.driver.switch_to.frame(self.driver.find_element_by_xpath('//*[@id="content-main"]/iframe[2]')) # allure.attach(self.driver.save_screenshot(os.getcwd() + "\\" + "images\\" + str(uuid.uuid1()).replace("-", "") + ".png"), "报错页面", allure.attachment_type.PNG) self.driver.find_element_by_xpath('//*[@id="name"]').send_keys('appman') #退出iframe self.driver.switch_to.default_content() print("ok---200")
def sliding(sliding_url): """ 滑动函数, :param sliding_url: 需要滑动的网页 :return: """ print 'sliding is run' driver = webdriver.Firefox() driver.delete_all_cookies() driver.get(sliding_url) try: element = WebDriverWait(driver, 5).until( EC.presence_of_element_located( (By.XPATH, '//span[@id="nc_1_n1z"]'))) except: print 'Not find element' dr1 = ActionChains(driver) dr1.click_and_hold(element).pause(1) dr1.move_by_offset(100, 0).pause(1).move_by_offset(160, 0) dr1.perform() time.sleep(1) for cookie in driver.get_cookies(): # print cookie if cookie['name'] == 'x5sec': # print '%s -> %s' % (cookie['name'], cookie['value']) cookie_value = cookie['value'] driver.quit() time.sleep(1) send_cookie(cookie_value)
def open_url(self, url): options = webdriver.ChromeOptions() # 不加载图片,加快访问速度 # options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) # 此步骤很重要,设置为开发者模式,防止被各大网站识别出来使用了Selenium options.add_experimental_option('excludeSwitches', ['enable-automation']) options.add_argument('--headless') browser = webdriver.Chrome( executable_path="G:\chromedriver_win32\chromedriver.exe", options=options) wait = WebDriverWait(browser, 10) # 超时时长为10s # 打开网页 browser.get(url) try: WebDriverWait(browser, 5, 0.5).until( EC.presence_of_element_located( (By.ID, "nc_1__scale_text"))) # 等待滑动拖动控件出现 swipe_button = browser.find_element_by_xpath( '//*[@id="nc_1__scale_text"]/span') # 获取滑动拖动控件 # 模拟拽托 action = ActionChains(browser) # 实例化一个action对象 action.click_and_hold( swipe_button).perform() # perform()用来执行ActionChains中存储的行为 action.reset_actions() action.move_by_offset(580, 0).perform() # 移动滑块 except Exception as e: print('get button failed: ', e)
def move_slider(self, move_x): track = self.simulation_track(move_x - self.error) move_element = self.driver.find_element_by_class_name( 'geetest_slider_button') action = ActionChains(self.driver) action.click_and_hold(move_element).perform() time.sleep(0.3) for i, x in enumerate(track): action.move_by_offset(x, 0).perform() if i < 1 / 3 * len(track): time.sleep(0.01) if i < 1 / 2 * len(track): time.sleep(0.02) elif i < 3 / 4 * len(track): time.sleep(0.04) elif i < 5 / 6 * len(track): time.sleep(0.08) else: time.sleep(0.1) action = ActionChains(self.driver) time.sleep(0.5) action.release().perform() time.sleep(3) try: self.driver.find_element_by_class_name('geetest_slider_button') return 0 except: return 1
def click_on_element_by_coordinates(cls, element_coordinates: tuple): x_webdriver = element_coordinates[0] y_webdriver = element_coordinates[1] actions = ActionChains(cls.driver) actions.move_by_offset(x_webdriver, y_webdriver) actions.click() actions.perform()
def __slide_url(self, slide_block_locator="None", slide_background_locator='None'): """ 一键滑动:使用cv2找出图像中最佳匹配位置,拖动滚动条实现滚动 :param slide_block_locator: 滑块元素定位表达式 :param slide_background_locator: 滑块背景图定位表达式 :return: """ # 滑动模块类 slide_1 = Slide(self.drive) # 下载保存照片 block_path = slide_1.slide_img(host=self.__get_element_src(slide_block_locator), filepath='../data/imgs/slide_block.png') background_path = slide_1.slide_img(host=self.__get_element_src(slide_background_locator), filepath='../data/imgs/slide_background.png') # 获取x轴坐标 x = slide_1.find_pictrue(target=block_path, template=background_path) # 计算图片缩放比 计算拖动距离 保存的图片为原始比例,但页面的显示的照片又缩放,这里获取缩放比例 # 由于滑块的x坐标不为0, 此处的32时通过画图获取的 x = int(x * slide_1.background_width / self.width) - 32 '''滑动''' action = ActionChains(self.drive) # 点击滑块 action.click_and_hold(self.__locator_element(slide_block_locator)).perform() action.move_by_offset(x, 0).perform() self.sleep('1')
def test_action_chains_鼠标(): driver = webdriver.Chrome() driver.implicitly_wait(10) driver.maximize_window() driver.get('http://sahitest.com/demo/mouseover.htm') write = driver.find_element_by_xpath( '//input[@value="Write on hover"]' ) # 鼠标移动到此元素,在下面的input框中会显示“Mouse moved” blank = driver.find_element_by_xpath( '//input[@value="Blank on hover"]') # 鼠标移动到此元素,会清空下面input框中的内容 result = driver.find_element_by_name('t1') action = ActionChains(driver) action.move_to_element(write).perform() # 移动到write元素,显示“Mouse moved” print(result.get_attribute('value')) # action.move_to_element(blank).perform() action.move_by_offset( 10, 50).perform() # 移动到距离当前位置(10,50)的点,与上句效果相同,移动到blank上,清空 print(result.get_attribute('value')) action.move_to_element_with_offset( blank, 10, -40).perform() # 移动到距离blank元素(10,-40)的点,可移动到write上 print(result.get_attribute('value')) time.sleep(2) driver.quit()
def move_mouse_cursor_to_webelement(self, driver, xElement): from selenium import webdriver from selenium.webdriver import ActionChains #wait = WebDriverWait(driver, 10) #utilities.action_utils.Driver_Actions().driver_page_home_action(driver) #self.driver_page_home_action(driver) try: time.sleep(1) myX = xElement.location['x'] myY = xElement.location['y'] size = xElement.size w = size['width'] h = size['height'] #print(str(myX) + " " + str(myY)) #print("Width = " + str(w) + ", Height = " + str(h)) action = ActionChains(driver) action.move_by_offset(int(myX), int(myY)).perform() action.move_to_element(xElement).perform() #action.perform() #return driver except Exception as e00: self.retry_move_cursor_to_webelement(driver, xElement) #utilities.action_utils.Driver_Actions().scroll_and_search_into_view_of_xElement(driver, xElement=xElement) #action.perform() return driver
def drag(self, x_offset, y_offset): 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.click_and_hold() actions.move_by_offset(x_offset, y_offset) actions.release().perform()
def bot_mitigation(self): """Three commands for bot-detection mitigation when getting a site.""" # bot mitigation 1: move the randomly around a number of times window_size = self.webdriver.get_window_size() num_moves = 0 num_fails = 0 while num_moves < NUM_MOUSE_MOVES + 1 and num_fails < NUM_MOUSE_MOVES: try: if num_moves == 0: # move to the center of the screen x = int(round(window_size['height']/2)) y = int(round(window_size['width']/2)) else: # move a random amount in some direction move_max = random.randint(0, 500) x = random.randint(-move_max, move_max) y = random.randint(-move_max, move_max) action = ActionChains(self.webdriver) action.move_by_offset(x, y) action.perform() num_moves += 1 except MoveTargetOutOfBoundsException: num_fails += 1 self.log.warning("Mouse movement out of bounds," "trying a different offset...") # bot mitigation 2: scroll in random intervals down page scroll_down(self.webdriver) # mitigation 3: randomly wait so that page visits appear irregularly time.sleep(random.randrange(RANDOM_SLEEP_LOW, RANDOM_SLEEP_HIGH))
def handle_driver(driver, ac1): dr = ActionChains(driver) dr.move_to_element(ac1).click_and_hold(ac1).perform() time.sleep(2.5) dr.move_by_offset(573, 381).perform() time.sleep(0.3) file_name = 'bi.png' driver.save_screenshot(file_name) # dr.release().perform() driver.save_screenshot('bi2.png') im = Image.open(file_name) box = (562, 224, 822, 340) region = im.crop(box) # region.show() file_cut = 'cut.png' region.save(file_cut) time.sleep(1) move_num = handl.scan_img(file_cut) print move_num # ActionChains(driver).drag_and_drop_by_offset(ac1, move_num-7, 0).perform() # time.sleep(1) # dr.move_to_element(ac1).perform() driver.save_screenshot('bi3.png') dr.move_by_offset(0, 768).release().perform() driver.save_screenshot('biok.png') time.sleep(1) driver.save_screenshot('biok2.png') dr.drag_and_drop_by_offset(ac1, 0, move_num-7).perform() driver.save_screenshot('biok3.png') driver.quit()
def test_toggle_snap(graph_cases, snap): """ :type graph_cases: qmxgraph.tests.conftest.GraphCaseFactory """ graph = graph_cases('1v') selenium = graph.selenium # If snap is enabled, it should move to closest grid block (which are # always multiples of 10, as 10 is grid size). By default snap is enabled. if not snap: selenium.execute_script("api.toggleSnap()") vertex = graph.get_vertex() x, y = graph.get_vertex_position(vertex) w, h = graph.get_vertex_size(vertex) actions = ActionChains(selenium) actions.move_to_element(vertex) actions.move_by_offset(w / 2., h / 2.) actions.drag_and_drop_by_offset(None, 66, 66) actions.perform() vertex = graph.get_vertex() def expected(v): result = v + 66 if snap: result = math.ceil(result / 10.) * 10 return result assert int(vertex.get_attribute('width')) == w assert int(vertex.get_attribute('height')) == h assert int(vertex.get_attribute('x')) == expected(x) assert int(vertex.get_attribute('y')) == expected(y)
def test_blockly_karel_transition(self): """ Testing that changing Blockly will be saved in Karel code """ self.driver.get(self.host + "/index.html") self.driver.execute_script('window.localStorage.clear();') actionChains = ActionChains(self.driver) #going into blockly window rb = self.driver.find_element_by_class_name("blockly-button") self.assertIsNotNone(rb) rb.click() #selecting and draging "move" piece on to the canvas placing it into "for loop block" karel = self.driver.find_element_by_id(":1") karel.click() getBlocklyElement(self, 0) piece = self.driver.find_element_by_class_name("blocklySelected") actionChains.click_and_hold(piece).perform() actionChains.move_by_offset(140, 35).release(piece).perform() #back to karel back = self.driver.find_elements_by_class_name("btn-primary")[1] self.assertIsNotNone(back) back.click() #checking if code is in sync with blockly code = self.driver.find_element_by_class_name("CodeMirror-code") self.assertEqual(code.text, '1\nfrom karel import * \n2\nmove()\n3')
def do_login(driver, name_pwd): print('=====do_login=====') # 切换到账号登录tab driver.find_element_by_xpath( '/html/body/div[2]/div/div/div[1]/a[2]').click() driver.find_element_by_id('userName').send_keys(name_pwd[0]) driver.find_element_by_id('password').send_keys(name_pwd[1]) # 获取活动模块 button = driver.find_element_by_xpath( '//*[@id="siller1_dt_child_content_containor"]/div[3]') action = ActionChains(driver) action.click_and_hold(button).perform() # 滑动模块 x = 0 while True: action.move_by_offset(xoffset=x, yoffset=0).perform() x += 50 print(x) if x >= 274: break time.sleep(1) action.release().perform() # 点击登录按钮 driver.find_element_by_xpath('//*[@id="submit"]').click() time.sleep(2)
def move(dis): action = ActionChains(driver) action.click_and_hold(driver.find_element_by_css_selector("div.geetest_slider_button")) trace_list = get_trace_list(dis) for i in trace_list: action.move_by_offset(i, 0) action.release().perform()
def move_by_offset_and_click(self, xoffset=0, yoffset=0, action='click'): """ 移动到指定坐标 :param xoffset: :param yoffset: :return: """ action_select = ['click', 'double_click', 'context_click'] if action not in action_select: LOG_DEBUG('action: {}参数错误, 可选参数为: {}'.format(action, action_select)) try: LOG_DEBUG('移动到坐标 x:{}, y:{}, 点击坐标'.format(xoffset, yoffset)) actions = ActionChains(self.driver) actions.move_by_offset(xoffset, yoffset) if action == 'click': actions.click() elif action == 'double_click': actions.double_click() elif action == 'context_click': actions.context_click() else: pass actions.perform() except Exception as e: LOG_DEBUG('移动坐标失败: {}'.format(e))
def login_by_qcode(): qcode = driver.find_element_by_id("J_QRCodeImg") action = ActionChains(driver) action.reset_actions() action.move_to_element(qcode) action.move_by_offset(20, -20).click() action.perform() while True: url = driver.current_url if not url.startswith("https://login.taobao.com"): cookies = driver.get_cookies() res = "" for cookie in cookies: res += cookie.get('name') + '=' + cookie.get('value') + ';' res = res[:-1] print(res) break try: refresh = driver.find_element_by_class_name("J_QRCodeRefresh") refresh.click() except: pass time.sleep(6)
def getBlocklyElementRect(self, elementNo): blocklyCanvas = self.driver.find_elements_by_class_name("blocklyBlockCanvas")[1] piece = blocklyCanvas.find_elements_by_tag_name("rect")[elementNo] time.sleep(.5) actionChains3= ActionChains(self.driver) actionChains3.click_and_hold(piece).perform() actionChains3.move_by_offset(-20,-20).move_by_offset(270,-210).release(piece).perform()
def search_by_keyword(keyword): url = "https://www.twinword.com/writer/" display = Display(visible=0, size=(1920, 1080)) display.start() driver = webdriver.Chrome('/home/ubuntu/chromedriver') driver.get(url) # time.sleep(3) div = driver.find_element_by_css_selector("div.redactor-editor") driver.execute_script("arguments[0].innerHTML = '" + keyword + "'", div) # driver.execute_script("arguments[0].setAttribute('class', 'asdlknsvklsn')", div) actions = ActionChains(driver) actions.move_by_offset(125, 255) actions.click() # time.sleep(1) actions.click() actions.click() actions.click() actions.perform() time.sleep(1) suggestions = driver.find_elements_by_css_selector( "div.dropDownBox_suggestion") results = [] results.append(keyword) for suggestion in suggestions: results.append(suggestion.text) # if(len(results)>=10): # break print(results) driver.close() # print(div.text) return jsonify(results)
def dealCheck(browser): js1 = '''Object.defineProperties(navigator,{ webdriver:{ get: () => false } }) ''' js2 = '''window.navigator.chrome = { runtime: {}, }; ''' js3 = '''Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); ''' js4 = '''Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5,6], }); ''' browser.execute_script(js1) browser.execute_script(js2) browser.execute_script(js3) browser.execute_script(js4) time.sleep(1) while True: buttons = browser.find_elements_by_id('nc_1_n1z') if len(buttons) > 0: print("no!") action = ActionChains(browser) action.click_and_hold(buttons[0]).perform() action.reset_actions() action.move_by_offset(320, 0).perform() time.sleep(3) js1 = '''Object.defineProperties(navigator,{ webdriver:{ get: () => false } }) ''' js2 = '''window.navigator.chrome = { runtime: {}, }; ''' js3 = '''Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); ''' js4 = '''Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5,6], }); ''' browser.execute_script(js1) browser.execute_script(js2) browser.execute_script(js3) browser.execute_script(js4) else: break
def set_range(driver, el,): ac = ActionChains(driver) ac.move_to_element(el) ac.click_and_hold() ac.move_by_offset(0, 50) ac.release() ac.perform()
def move2(self, browser): """ complete actions of sliding captcha """ self.save_img(browser) self.calc_position(browser) offset = self.get_offset('./captcha/template1.jpg', './captcha/template2.jpg') print("offset calc by get_offset() is: {}".format(offset)) tracks = self.get_tracks(offset) print("the track array is: {}".format(tracks)) slider = browser.find_element_by_class_name("JDJRV-slide-btn") action = ActionChains(browser) action.click_and_hold(slider).perform() action.reset_actions() for i in tracks: action.move_by_offset(round(i), 0).perform() print('should move--<{}>--'.format(i)) print('moving--<{}>--'.format(slider.location['x'])) time.sleep(0.1) # in order to prevent accumulation actions action.reset_actions() # useful # action = ActionChains(browser) # useful time.sleep(4) action.release().perform()
def login(self): # 利用浏览器进行登录 self.driver.get("https://www.binance.com/login.html") # 输入框中填入值 element_username = self.driver.find_element_by_id('email') element_passw = self.driver.find_element_by_id('pwd') element_username.send_keys(self.username) element_passw.send_keys(self.passw) # 控制滑块拖动 action_chains = ActionChains(self.driver) element_btn = self.driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') action_chains.click_and_hold(on_element=element_btn) action_chains.move_by_offset(400, 0) action_chains.perform() element_error = self.driver.find_element_by_xpath( '//*[@id="nc_1__scale_text"]') while 1: if element_error.text == "Please input verification code": # 验证验证码的正确性 self.check_captcha(self.driver) submit = self.driver.find_element_by_id("login-btn") submit.send_keys(Keys.ENTER) break else: pass time.sleep(3) print("登录成功...") cookies = dict() for cookie in self.driver.get_cookies(): cookies[cookie['name']] = cookie['value'] self.cookies = cookies self.driver.quit()
def slide_discern(): print("滑块验证码验证中。。。") # try: # 获取到需滑动的按钮 source = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') action = ActionChains(driver) # 按住左键不放 action.click_and_hold(source).perform() # 开始滑动 distance = 348 # 模拟以人为速度拖动 track = get_track(distance) # ttt = [23, 81, 224] for i in track: try: action.move_by_offset(xoffset=i, yoffset=0).perform() # perform --- 执行所有准备好的Action # action.reset_actions() # reset_actions --- 清空所有准备好的Action,这个需要selenium版本3.0以上 # time.sleep(0.4) except StaleElementReferenceException as e: action.release().perform() # 释放鼠标 driver.find_element_by_xpath('//div[@class="errloading"]/span/a').click() source = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]') # 获取到需滑动的按钮 action = ActionChains(driver) action.click_and_hold(source).perform() # 按住左键不放 # action.reset_actions() # 清除之前的action action.move_by_offset(xoffset=i, yoffset=0).perform() # perform --- 执行所有准备好的Action # 释放鼠标 action.release().perform()
def slider_verification_code_163yidun(browser, cut_element, back_element, slider_element): while True: # 将验证码的背景图和滑块图片下载下来 download_img_by_src(browser, back_element, 'back.jpg') download_img_by_src(browser, cut_element, 'cut.png') sleep(1) cut_image, back_image = read_img_file('cut.png', 'back.jpg') distance = get_distance(back_img=back_image, cut_img=cut_image) print(distance) if distance: action = ActionChains(browser) action.click_and_hold( browser.find_element(slider_element[0], slider_element[1])).perform() # tracks = get_track(distance) # for i in tracks: action.move_by_offset(xoffset=distance, yoffset=-1).perform() action = ActionChains(browser) sleep(1) action.release().perform() sleep(5) if re.findall("订单", browser.page_source, re.S): break if '失败过多,点此重试' in browser.page_source: browser.find_element_by_xpath( "//span[@class='yidun_tips__text']").click()
def save_cookies(self): self.browser.implicitly_wait(10) self.browser.maximize_window() self.browser.find_element_by_xpath( '//input[@name="fm-login-id"]').send_keys('***') self.browser.find_element_by_xpath( '//input[@name="fm-login-password"]').send_keys('***') # 解决滑块 slide_block = self.browser.find_element_by_xpath('//*[@id="nc_1_n1z"]') if (slide_block.is_displayed()): action = ActionChains(self.browser) action.click_and_hold(on_element=slide_block) action.move_by_offset(xoffset=258, yoffset=0) action.pause(0.5).release().perform() # perform指定动作链 self.browser.find_element_by_xpath( '//button[@class="fm-button fm-submit password-login"]').click() time.sleep(5) if "login_unusual" in self.browser.current_url: print("gg了,要手机验证码了,救命啊啊啊啊啊") input("输入手机验证码啦:") self.cookies = '; '.join(item for item in [ item["name"] + "=" + item["value"] for item in self.browser.get_cookies() ]) with open(COOKIES_FILE_PATH, 'w', encoding='utf-8') as file: file.write(self.cookies) print("cookie写入成功:", self.cookies)
class SliderCaptcha(object): """滑块验证码""" def __init__(self): self.url = "http://www.porters.vip/captcha/sliders.html" self.driver_path = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe" self.browser = webdriver.Chrome(executable_path=self.driver_path) self.wait = WebDriverWait(self.browser, timeout=20) self.action_chains = ActionChains(self.browser) def __str__(self): self.browser.close() def run(self): self.browser.get(url=self.url) time.sleep(1) # 获取滑块元素对象 # hover = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "hover"))) # 通过类选择器来定位滑块元素 hover = self.wait.until(EC.presence_of_element_located((By.ID, "sliderblock"))) # 模拟人为拖动滑块 # 通过分析CSS样式得出滑块需要滑动的轨迹为340px self.action_chains.click_and_hold(hover).perform() # 点击并按住滑块不松手 self.action_chains.move_by_offset(340, 0) # 设置滑块轨迹, 模拟滑块横向滑动340px,纵向滑块滑动距离为0px self.action_chains.release().perform() # 松快鼠标 time.sleep(5)
def half_rotate(self): ac = ActionChains(self.driver) ac.move_to_element(self.tourImage()) ac.click_and_hold() ac.move_by_offset(self.tourImage().size["width"] / 2, 0) ac.release() ac.perform()
def swich_btn(self): button = self.find_element(self.swichbut_loc) action = ActionChains(self.driver) action.click_and_hold(button).perform() sleep(1) action.move_by_offset(400, 0).perform() action.reset_actions()
def click_on(x, y, driver): xa, ya = get_adjusted_coords(x, y) action = ActionChains(driver) action.reset_actions() action.move_by_offset(xa, ya) action.click() action.perform()
def login(self, username='', password=''): username = '******' password = '******' self.brower.get('http://vbooking.ctrip.com/ivbk/accounts/login') try: self.brower.find_element_by_xpath( '//*[@id="loginpanel_container"]/div[1]/div[1]/form/dl[1]/dd/input' ).send_keys(username) sleep(2) self.brower.find_element_by_xpath( '//*[@id="loginpanel_container"]/div[1]/div[1]/form/dl[2]/dd/input' ).send_keys(password) self.brower.execute_script( 'Object.defineProperties(navigator,{webdriver:{get:() => false}});' ) status = self.brower.execute_script('window.navigator.webdriver') sleep(2) button = self.brower.find_element_by_xpath( '//*[@id="verification-code"]/div[1]/div[2]') action = ActionChains(self.brower) action.click_and_hold( button).perform() # perform()用来执行ActionChains中存储的行为 action.reset_actions() action.move_by_offset(140, 0).perform() sleep(0.2) action.move_by_offset(140, 0).perform() self.brower.find_element_by_xpath( '//*[@id="loginpanel_container"]/div[1]/div[1]/form/button' ).click() sleep(1) # 登录逻辑中保存session for cookie in self.brower.get_cookies(): self.session.cookies.set_cookie( cookielib.Cookie(version=0, name=cookie['name'], value=cookie['value'], port='80', port_specified=False, domain=cookie['domain'], domain_specified=True, domain_initial_dot=False, path=cookie['path'], path_specified=True, secure=cookie['secure'], rest={}, expires=cookie['expiry'] if "expiry" in cookie else None, discard=False, comment=None, comment_url=None, rfc2109=False)) self.session.cookies.save() return True except Exception as e: print("登录失败", e) return False
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 action_elements_events(self, element_menu, drag_divs): action = ActionChains(self.driver) action.move_to_element(element_menu).click(element_menu) action.click_and_hold(drag_divs) action.move_by_offset(35, 35) action.move_by_offset(15, 20) action.move_by_offset(55, 15) action.release() action.perform() event_start = self.driver.find_element_by_xpath("//li[@id = 'event-start']/span[2]").text event_drag = self.driver.find_element_by_xpath("//li[@id='event-drag']/span[2]").text event_stop = self.driver.find_element_by_xpath("//li[@id = 'event-stop']/span[2]").text return event_start, event_drag, event_stop
def answer_problem(self, correctness): """ Answer image problem. """ offset = 25 if correctness == 'correct' else -25 input_selector = ".imageinput [id^='imageinput_'] img" input_element = self.problem_page.q(css=input_selector)[0] chain = ActionChains(self.browser) chain.move_to_element(input_element) chain.move_by_offset(offset, offset) chain.click() chain.perform()
def move_slider(self, slider, offset=0.0): """Click somewhere in an horizontal slider. The position is given in fraction of its width: *offset* from 0 to 1.""" width = slider.size['width'] action_chains = ActionChains(self.driver) # Move to the middle of the slider (default), then to its leftmost point action_chains.move_to_element(slider).move_by_offset(-width/2.0, 0) # Double-click twice to know where the cursor is. #action_chains.context_click().context_click() # Need to perform() because it seems to bug with move_by_offset otherwise action_chains.perform() # Offset to the right action_chains.move_by_offset(width * offset, 0) # Double-click twice to know where the cursor is #action_chains.context_click().context_click() action_chains.click().perform()
def test_remove_tag(self): old_tag_num = len(self.browser.find_by_css('span.taggit_tag')) driver = self.browser.driver actions = ActionChains(driver) tag_link = driver.find_element_by_css_selector('#taggit_tags a') actions.move_to_element(tag_link) actions.move_by_offset(25, 10) actions.click() actions.perform() document_list_url = \ self.live_server_url + reverse('documents.views.list_documents') self.assertEquals(self.browser.url, document_list_url) new_tag_num = len(self.browser.find_by_css('span.taggit_tag')) self.assertEquals(new_tag_num, old_tag_num - 1) # import time; time.sleep(3) self.browser.quit()
def add_object_to_workflow(self, obj_path, target_name): """ Add `obj_path` object to `target_name` in workflow. """ for retry in range(3): try: obj = self.find_object_button(obj_path) target = self.get_workflow_figure(target_name) chain = ActionChains(self.browser) chain.move_to_element(obj) chain.click_and_hold(obj) chain.move_to_element(target.root) chain.move_by_offset(2, 1) chain.release(None) chain.perform() except StaleElementReferenceException: if retry < 2: logging.warning("add_object_to_workflow:" " StaleElementReferenceException") else: raise else: break
def test_teacher_exclude_certain_questions_14852(self): """Exclude certain quesitons. Steps: If the user has more than one course, click on a CC course name Click "Question Library" from the user menu Select a section or chapter Click "Show Questions" Hover over the desired question and click "Exclude question" Expected Result: Question is grayed out """ self.ps.test_updates['name'] = 'cc2.11.002' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['cc2', 'cc2.11', 'cc2.11.002', '14852'] self.ps.test_updates['passed'] = False # Test steps and verification assertions self.teacher.login() self.teacher.find( By.XPATH, '//a[contains(@href,"/cc-dashboard")]' ).click() self.teacher.open_user_menu() self.teacher.find( By.LINK_TEXT, 'Question Library' ).click() self.teacher.find( By.XPATH, '//div[@class="section"]//span[@class="chapter-section" ' + 'and @data-chapter-section="1.2"]' ).click() self.teacher.driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);") self.teacher.find( By.XPATH, '//button[text()="Show Questions"]' ).click() self.teacher.wait.until( expect.visibility_of_element_located( (By.XPATH, '//div[@class="exercises"]') ) ) self.teacher.sleep(1) i = 1 question = None # loop finding a question that is not yet excleded # there are 9 question in the exact textbook and chpater this test # is searching. limiting loop at 7 incase questions are removed. while i < 8: question = self.teacher.find( By.XPATH, '//div[@class="exercises"]/div[' + str(i) + ']' ) if ('is-selected' not in question.get_attribute('class')): break i += 1 Assignment.scroll_to(self.teacher.driver, question) self.teacher.sleep(1) actions = ActionChains(self.teacher.driver) actions.move_to_element(question) # way to stall because not sure how to add wait in action chain for _ in range(50): actions.move_by_offset(-1, 0) actions.click() actions.move_by_offset(-50, -300) actions.perform() self.teacher.sleep(0.5) question_excluded = self.teacher.find( By.XPATH, '//div[@class="exercises"]/div[' + str(i) + ']' ).get_attribute('class') assert('is-selected' in question_excluded), 'question not excluded' self.ps.test_updates['passed'] = True
def resize_editor(self, editor): '''ensure that the editor is not covering the library (or else we cannot drag things from it!)''' browser = self.browser page_width = browser.get_window_size()['width'] lib_tab = self('library_tab').find_element_by_xpath('..') lib_width = lib_tab.size['width'] lib_position = lib_tab.location['x'] dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] # how much overlap do we have? overlap = lib_position - (dialog_position + dialog_width) if overlap < 0: # we are overlapping # check to see if we have enough room to move out of the way if page_width < dialog_width + lib_width: # not enough, need to rezize the editor # look for the resize handle sibblings = dialog_title.find_elements_by_xpath('../../div') handle = None for sib in sibblings: if "ui-resizable-se" in sib.get_attribute('class'): handle = sib # do the resizing chain = ActionChains(browser) chain.click_and_hold(handle) # we can resize editor down to 425px, any less and we cover drop targets chain.move_by_offset(450 - dialog_width, 0).perform() # must click because release is not working. why? I do not know. chain.click().perform() chain.release(None).perform() # recalculate the overlap dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] overlap = lib_position - (dialog_position + dialog_width) # We are good, move out! chain = ActionChains(browser) chain.click_and_hold(editor('dialog_title').element) chain.move_by_offset(overlap, 0).perform() # must click because release is not working. why? I do not know. chain.click().perform() chain.release(None).perform() # recalculate the overlap dialog_title = editor('dialog_title').find_element_by_xpath('../..') dialog_width = dialog_title.size['width'] dialog_position = dialog_title.location['x'] overlap = lib_position - (dialog_position + dialog_width) if overlap < 0: # we still have a problem. eq(True, False, "Could not move or rezise the editor dialog so it is not " "overlapping the library. The browser window is too small")
def test_teacher_report_errata_about_assessments_in_cc_14858(self): """Report errata about assessments in Concept Coach. Steps: If the user has more than one course, click on a CC course name Click "Question Library" from the user menu Select a section or chapter Click "Show Questions" Hover over the desired question and click "Question details" Click "Report an error" Expected Result: A new tab with the assessment errata form appears, with the assessment ID already filled in """ self.ps.test_updates['name'] = 'cc2.11.005' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['cc2', 'cc2.11', 'cc2.11.005', '14858'] self.ps.test_updates['passed'] = False # Test steps and verification assertions self.teacher.login() self.teacher.find( By.XPATH, '//a[contains(@href,"/cc-dashboard")]' ).click() self.teacher.open_user_menu() self.teacher.find( By.LINK_TEXT, 'Question Library' ).click() self.teacher.find( By.XPATH, '//div[@class="section"]//span[@class="chapter-section" ' + 'and @data-chapter-section="1.2"]' ).click() self.teacher.driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);") self.teacher.find( By.XPATH, '//button[text()="Show Questions"]' ).click() self.teacher.wait.until( expect.visibility_of_element_located( (By.XPATH, '//div[@class="exercises"]') ) ) self.teacher.sleep(1) question = self.teacher.find( By.XPATH, '//div[@class="exercises"]/div[1]' ) actions = ActionChains(self.teacher.driver) actions.move_to_element(question) # way to stall because not sure how to add wait in action chain for _ in range(50): actions.move_by_offset(1, 0) actions.click() actions.perform() self.teacher.sleep(0.5) exercise_id = self.teacher.wait.until( expect.visibility_of_element_located( (By.XPATH, '//span[@class="exercise-tag" and contains(text(),"ID:")]') ) ).text question = self.teacher.find( By.XPATH, '//div[@class="action report-error"]' ).click() window_with_form = self.teacher.driver.window_handles[1] self.teacher.driver.switch_to_window(window_with_form) self.teacher.wait.until( expect.visibility_of_element_located( (By.XPATH, '//div[text()="Report Content Errors"]') ) ) self.teacher.find( By.XPATH, '//input[@value="' + exercise_id[4:] + '"]') self.ps.test_updates['passed'] = True
def retriveRatings(browser,mainWind,url): browser.driver.get(url) windows=browser.driver.window_handles for wind in windows: if wind!=mainWind: browser.driver.switch_to_window(wind) browser.driver.close() browser.driver.switch_to_window(mainWind) # Azioni per andare a chiudere il popup nel caso apparisse actions = ActionChains(browser.driver) actions.move_by_offset(40,50).click() actions.perform() # Filtraggio dei Rates per RATINGS e ATTRAZIONI try: ratesFilter=browser.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "ul.cs-contribution-bar > li[data-filter='RATINGS_ALL'] > a"))) ratesFilter.click() except TimeoutException: print "\n\nNon e presente il filtro per RATINGS!" return try: dataFilter=browser.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.cs-filter-bar ul > li[data-filter='RATINGS_ATTRACTIONS']"))) dataFilter.click() except TimeoutException: print "\n\nNon e presente il filtro per ATTRACTIONS!" return # Recupero dei dati dei vari RATES nextPage,globDates,globLocations,globAttractions,globRates=True,[],[],[],[] while nextPage: try: dates=browser.wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.cs-rating-date"))) locations=browser.wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.cs-rating-geo"))) attractions=browser.wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.cs-rating-location a"))) rates=browser.wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.cs-rating img"))) dates=[date.text for date in dates] locations=[loc.text for loc in locations] attractions=[attr.text for attr in attractions] rates=[rate.get_attribute("content") for rate in rates] print "\n\nATTRAZIONI: {}\n\nLOCATIONS: {}\n\nRATES: {}\n\nDATES: {}".format(attractions,locations,rates,dates) globDates.extend(dates) globLocations.extend(locations) globAttractions.extend(attractions) globRates.extend(rates) except TimeoutException: print "\nTempo Terminato! Elementi non trovati" try: nextPage=browser.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#cs-paginate-next"))) actions=ActionChains(browser.driver) actions.click(nextPage) actions.perform() except WebDriverException: print "\nNEXT non presente!" nextPage=None return zip(globDates,globLocations,globAttractions,globRates)
def move_to_element(self, ele): action = ActionChains(self.driver) action.move_to_element(ele) action.move_by_offset(1, 1) action.perform()
class Login(): def __init__(self): self.email='*****@*****.**' self.password='******' self.browser = webdriver.Chrome() self.browser.maximize_window() self.wait=WebDriverWait(self.browser,10) self.browser.get('https://auth.geetest.com/login/') self.action=ActionChains(self.browser) def user(self): email=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[1]/div/div[1]/input') password=self.browser.find_element(By.XPATH,'//*[@id="base"]/div[2]/div/div/div[3]/div/form/div[2]/div/div[1]/input') self.action.click(email).perform() time.sleep(1) email.send_keys(self.email) time.sleep(1) self.action.click(password).perform() time.sleep(1) password.send_keys(self.password) def position(self): image=self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img'))) location=image.location location['x']=location['x'] location['y']=location['y'] size=image.size size['height']=size['height'] size['width']=size['width'] rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) return rangle def get_position1(self): #获取图片位置 button1=self.browser.find_element(By.CLASS_NAME,'geetest_radar_tip') self.action.click(button1).perform() #self.browser.switch_to.frame(self.browser.find_element_by_tag_name("iframe")) #image1=self.browser.find_element(By.XPATH,'/html/body/div[3]/div[2]/div[1]/div/div[1]/div[1]/div/a/div[1]/canvas') rangle=self.position() return rangle def get_position2(self): button2=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button') button2.click() rangle=self.position() return rangle def image(self,rangle): screenshot=self.browser.get_screenshot_as_png() screenshot=Image.open(BytesIO(screenshot)) captche=screenshot.crop(rangle) return captche def get_image1(self): rangle=self.get_position1() time.sleep(2) captche=self.image(rangle) width=captche.size[0] height=captche.size[1] #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS) captche.save('a.png') return captche def get_image2(self): rangle=self.get_position2() time.sleep(3) captche=self.image(rangle) width=captche.size[0] height=captche.size[1] #captche = captche.resize((int(width*0.8), int(height*0.8)),Image.ANTIALIAS) captche.save('b.png') return captche def is_pixel_equal(self, image1, image2, x, y): #判断两个像素是否相同 pixel1=image1.load()[x,y] pixel2=image2.load()[x,y] a=pixel1[0]-pixel2[0] b=pixel1[1]-pixel2[2] c=pixel1[2]-pixel2[2] threshold=60 if abs(a)<threshold and abs(b)<threshold and abs(c)<threshold: return True else: return False def get_gap(self, image1, image2): #获得缺口 left=60 #滑片宽度 for i in range(left, image1.size[0]): for j in range(image1.size[1]): if not self.is_pixel_equal(image1, image2, i, j): left = i return left return left def get_track(self,distance): #获得滑块的运动轨迹 track=[] current=0 v=0 t=0.2 m=distance*0.35 n=distance*0.7 while current<distance: if current<n: a=4 else: a=-6 v0=v v=v0+a*t move=v0*t+0.5*a*t*t current+=move track.append(round(move)) return track def move_to_grap(self): image1=self.get_image1() image2=self.get_image2() success=self.browser.find_element(By.CLASS_NAME,'geetest_success_radar_tip_content') slider=self.browser.find_element(By.CLASS_NAME,'geetest_slider_button') button=self.browser.find_element(By.CLASS_NAME,'ivu-btn') # +20多向前移动20的距离 distance=(self.get_gap(image1,image2)-6)+20 print(distance) track=self.get_track(distance) print(track) back_tracks=[-3,-3,-2,-2,-2,-2,-2,-1,-1,-1,-1] #待会回移的轨迹段 # while success.text!='验证成功': # for i in range(0,2): self.action.click_and_hold(slider) for x in track: self.action.move_by_offset(xoffset=x,yoffset=0) time.sleep(0.5) for y in back_tracks: self.action.move_by_offset(xoffset=y,yoffset=0) self.action.move_by_offset(xoffset=-3,yoffset=0) #小范围震荡 self.action.move_by_offset(xoffset=3,yoffset=0) time.sleep(0.5) self.action.release(slider) self.action.perform() time.sleep(2) # print(success.text) # if success.text=='验证成功': self.action.click(button).perform()
sleep(1) driver.find_element_by_id("remove_action").click() driver.switch_to_alert().accept() if driver.execute_script("return program.actions.length") == 0: print("Successful: Action deleted") else: print("Failure: Action deleted") sleep(1) actions.move_to_element(canvas).perform() sleep(1) actions = ActionChains(driver) actions.move_by_offset(0, -16) actions.click() actions.perform() sleep(1) actions = ActionChains(driver) actions.move_to_element(canvas) actions.click() actions.perform() sleep(1) driver.find_element_by_id("name").send_keys("b") driver.find_element_by_id("script").send_keys("print('hello world')") driver.find_element_by_id("agent-edit").click()