我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.webdriver.ActionChains()。
def download_book(url, name): chromedriver = '/home/rajdeep1008/Desktop/chromedriver' os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get(url) link = driver.find_element_by_link_text(name) actionChains = ActionChains(driver) actionChains.context_click(link) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.ARROW_DOWN) actionChains.send_keys(Keys.RETURN) actionChains.perform() while True: if not os.path.isfile('/home/rajdeep1008/Downloads/' + name + '.pdf'): time.sleep(5) else: break driver.quit() # download_book('http://it-ebooks.info/book/6719/', 'Android Studio Game Development')
def move_to(self, selector, click=False): ''' Move to the element matched by selector or passed as argument. Parameters ---------- selector: str Any valid CSS selector click: bool Whether or not to click the element after hovering defaults to False ''' try: elem = self.get_element(selector) action = webdriver.ActionChains(self.browser) action.move_to_element(elem) if click: action.click(elem) action.perform() except WebDriverException: print("move_to isn't supported with this browser driver.")
def drag_and_drop(self, from_selector, to_selector): ''' Drags an element into another. Parameters ---------- from_selector: str A CSS selector to search for. This can be any valid CSS selector. Element to be dragged. to_selector: str A CSS selector to search for. This can be any valid CSS selector. Target element to be dragged into. ''' from_element = self.get_element(from_selector) to_element = self.get_element(to_selector) ActionChains(self.browser).drag_and_drop(from_element, to_element).perform()
def _drag_and_drop(self, source, **kwargs): """Send values to a particular element, simulates typing into a element :Arguments: 1. source = a valid WebElement 2. target = a valid WebElement """ status = True print_info("Simulate a drag and drop") try: browser_instance = kwargs.get('browser') target = self._get_element(browser_instance, kwargs.get('target_locator')) if source is not None and target is not None: ActionChains(browser_instance).drag_and_drop(source, target).perform() except Exception as e: print_error("An Exception Occurred {}".format(e)) status = False return status
def click(self, element=None): if element is None: element = self.element click_element = ActionChains(self.browser).click_and_hold(element).release(element) click_element.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 click(self, element): actions = webdriver.ActionChains(self.driver) actions.move_to_element(element) actions.click(element) actions.perform()
def test_08_wrong_account(self, base_url, selenium): self.baseurl = base_url self.get(selenium, base_url + '/reconcile') src = selenium.find_element_by_id('ofx-1-OFXT4') tgt = selenium.find_element_by_id( 'trans-4').find_element_by_class_name('reconcile-drop-target') # get the innerHTML of both columns trans_div = selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') # drag and drop chain = ActionChains(selenium) chain.drag_and_drop(src, tgt).perform() # sleep a bit for the drag to stop sleep(1) # ensure both columns are still the same assert selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') == trans_div assert selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') == ofxtrans_div # ensure reconciled JS var is still the same assert self.get_reconciled(selenium) == {}
def test_09_wrong_amount(self, base_url, selenium): self.baseurl = base_url self.get(selenium, base_url + '/reconcile') src = selenium.find_element_by_id('ofx-1-OFXT4') tgt = selenium.find_element_by_id( 'trans-1').find_element_by_class_name('reconcile-drop-target') # get the innerHTML of both columns trans_div = selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') # drag and drop chain = ActionChains(selenium) chain.drag_and_drop(src, tgt).perform() # sleep a bit for the drag to stop sleep(1) # ensure both columns are still the same assert selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') == trans_div assert selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') == ofxtrans_div # ensure reconciled JS var is still the same assert self.get_reconciled(selenium) == {}
def test_10_wrong_acct_and_amount(self, base_url, selenium): self.baseurl = base_url self.get(selenium, base_url + '/reconcile') src = selenium.find_element_by_id('ofx-1-OFXT4') tgt = selenium.find_element_by_id( 'trans-3').find_element_by_class_name('reconcile-drop-target') # get the innerHTML of both columns trans_div = selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') ofxtrans_div = selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') # drag and drop chain = ActionChains(selenium) chain.drag_and_drop(src, tgt).perform() # sleep a bit for the drag to stop sleep(1) # ensure both columns are still the same assert selenium.find_element_by_id('trans-panel').get_attribute( 'innerHTML') == trans_div assert selenium.find_element_by_id('ofx-panel').get_attribute( 'innerHTML') == ofxtrans_div # ensure reconciled JS var is still the same assert self.get_reconciled(selenium) == {}
def check_auth_block(self): block = self.is_element_visible(LoginPageLocators.AUTH_BLOCK) if block: print("???????") actions = ActionChains() # actions.click_and_hold(block) # actions.move_by_offset(298, 0) actions.drag_and_drop_by_offset(self.findElement(LoginPageLocators.AUTH_BLOCK), 298, 0) actions.perform() time.sleep(2) flag = 1 if '????' in self.page_source() else 0 return flag else: print("????????????") flag = 1 return flag
def check_block(self): time.sleep(5) block = self.is_element_visible(CheckinPageLocators.BLOCK) if block: print("???????") actions = ActionChains() # actions.click_and_hold(block) # actions.move_by_offset(258, 0) actions.drag_and_drop_by_offset(block, 258, 0) actions.perform() time.sleep(2) flag = 1 if '????' in self.page_source() else 0 return flag else: print("????????????") flag = 1 return flag
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 reboot_verify_code(self): time.sleep(3) url = "https://ssl.captcha.qq.com/cap_union_new_show?aid=549000929&captype=&protocol=https&clientype=1&disturblevel=&apptype=2&noheader=0&color=&showtype=&fb=1&theme=&lang=2052&sess=BNMDwCNY6DHgvp19N75V1T62mdLntiP-PmMrPsSDfhljYM3PbvQa2YmZAiRB5yNaTGAJmEgshmGdugfAHEFElzFJsj25whcKd4PAMeNWF2tFbbPmPSMJ-zwovyzlm4D_WeopGav24sgESs1e47uDuSMicJPnaDpkbs3QCquiF2BmVEfgz-nW19mJEIEHdJxYn1XQd-wkyCU*&fwidth=0&uid=1473018671&cap_cd=-2wDJk7I9ogP7glTeXWzGfZ9pzEC6vuCa9cSAkbUMizVwgdtBrq8xA**&rnd=339939" # BS = BeautifulSoup(url,'lxml') # Bfind = BS.find('iframe')['src'] # self.browser.get(Bfind) self.browser.get(url) cap_input = self.browser.find_element_by_xpath('//*[@id="cap_input"]') cap_que_img = self.browser.find_element_by_xpath('//*[@id="cap_que_img"]') verify_btn = self.browser.find_element_by_xpath('//*[@id="verify_btn"]') self.dowload_verify_code_img(cap_que_img) verify_code_input = input("???: ") action_code = ActionChains(self.browser) cap_input.clear() action_code.move_to_element(cap_input).click().send_keys(verify_code_input) action_code.move_to_element(verify_btn).click() action_code.perform()
def DoubleClick(cls): log.step_normal("Element [%s]: Do DoubleClick()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.double_click(elements[cls.index]) action.perform() time.sleep(3) env.driver.switch_to_window(env.driver.window_handles[-1]) # env.driver.maximize_window() time.sleep(3) cls.__clearup()
def TypeIn(cls, value): """ input value without clear existed values """ if value == "": return log.step_normal(u"Element [%s]: TypeIn Value [%s]." % (cls.__name__, value)) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.send_keys_to_element(elements[cls.index], value) action.perform() cls.__clearup()
def Set(cls, value): log.step_normal("Element [%s]: Set [%s]." % (cls.__name__, value)) if isNumberType(value): value = str(value) cls.__wait() elements = env.threadlocal.BROWSER.find_elements(cls.by, cls.value) if elements[cls.index].tag_name == "select" or elements[cls.index].tag_name == "ul": cls.Select(value) else: elements[cls.index].clear() action = webdriver.ActionChains(env.threadlocal.BROWSER) action.send_keys_to_element(elements[cls.index], value) #???????? action.perform() cls.__clearup()
def Click(cls): log.step_normal("Element [%s]: Click()" % (cls.__name__)) cls.__wait() elements = env.threadlocal.BROWSER.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.threadlocal.BROWSER) action.click(elements[cls.index]) action.perform() #======================================================================= # action = webdriver.ActionChains(env.threadlocal.BROWSER) # action.key_up(Keys.CONTROL, elements[cls.index]) # action.perform() # # action.click(elements[cls.index]) # action.perform() #======================================================================= cls.__clearup()
def _goto_next_page(self): """ Click the next page element, Returns: The url of the next page or False if there is no such url (end of available pages for instance). """ next_url = '' element = self._find_next_page_element() if hasattr(element, 'click'): next_url = element.get_attribute('href') try: element.click() except WebDriverException: # See http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error # first move mouse to the next element, some times the element is not visibility selector = self.next_page_selectors[self.search_engine_name] if selector: try: next_element = WebDriverWait(self.webdriver, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, selector))) webdriver.ActionChains(self.webdriver).move_to_element(next_element).perform() # wait until the next page link emerges WebDriverWait(self.webdriver, 8).until( EC.visibility_of_element_located((By.CSS_SELECTOR, selector))) element = self.webdriver.find_element_by_css_selector(selector) next_url = element.get_attribute('href') element.click() except WebDriverException: pass # wait until the next page was loaded if not next_url: return False else: return next_url
def _mouse_over(self, element, **kwargs ): """Moving the mouse to the middle of an element """ status = False print_info("mouse over operation") browser_instance = kwargs.get('browser') if element is not None: ActionChains(browser_instance).move_to_element(element).perform() status = True return status
def _double_click_element(self, element, **kwargs): """ Double clicks on the provided element :Arguments: 1. element = a valid WebElement """ status = True print_info("Double click on element") try: browser_instance = kwargs.get('browser') ActionChains(browser_instance).double_click(element) except Exception as e: print_error("An Exception Occurred {}".format(e)) status = False return status
def _perform_keypress(self, element, **kwargs): """ This function expects to receive a browser instance through the "browser" argument and a key "keys" through the kwargs. The value for "keys" would be a list of keys tha need to pressed. """ status = True flag = False keys = kwargs.get('keys') actions = ActionChains(element) for key in keys: try: selenium_key = KEYS[key.upper()] except KeyError: print_error("{0} is not supported by Selenium.".format(key)) status = False else: flag = True actions.send_keys(selenium_key) if flag: actions.perform() sleep(2) return status
def test_1_view_alignment(self): actions = ActionChains(self.driver) rows = self.waitForAll('.public_fixedDataTable_bodyRow .public_fixedDataTableCell_cellContent') actions.double_click(rows[0]).perform() self.waitFor('.igv-modal', 3)
def robust_click(self, elt): """Click on the element, for the click() method is bugged half of the time""" self.driver.execute_script("arguments[0].scrollIntoView(true);", elt) action = ActionChains(self.driver) action.move_to_element(elt).click().perform()
def moveToElement(self, element): self.driver.execute_script("return arguments[0].scrollIntoView();", element) actions = webdriver.ActionChains(self.driver) actions.move_to_element(element) actions.perform()
def login(self, username, password): self.driver.get(url) elem_username = self.driver.find_element_by_name('username') elem_username.send_keys(username) elem_password = self.driver.find_element_by_name('password') elem_password.send_keys(password) # # ???? # action_chains = ActionChains(self.driver) # # elem_code = self.driver.find_element_by_name('geetest_validate') # elem_code = self.driver.find_element_by_class_name('gt_slider_knob') # location = elem_code.location # size = elem_code.size # moveX = 99 # ???? # action_chains.click_and_hold(elem_code) # time.sleep(5) # action_chains.drag_and_drop_by_offset(elem_code, moveX, 0).perform() # # action_chains.move_to_element_with_offset(elem_code, moveX, 0).perform() # elem_login = self.driver.find_element_by_class_name("loginbox-sbt btn-sub") # elem_login.submit() try: somedom = WebDriverWait(self.driver, 30) html = somedom.find_element_by_xpath("//div[@class='o-login fl']") print(html) finally: print("finally") pass self.driver.quit() # driver.quit()
def mouse_hover(self): """Hover the mouse over element :return: None """ webdriver.ActionChains(self.browser).move_to_element(self.element).perform()
def check_elements_are_visible(driver: webdriver, elements: list): take_screenshot(driver, NAME) for element in elements: selector = SCOPE_ELEMENTS[element.lower()] with selenium_action( driver, "Could not find '%s' on '%s' using '%s' selector", element, driver.current_url, selector): page_element = driver.find_element_by_css_selector(selector) if "firefox" not in driver.capabilities["browserName"].lower(): logging.debug("Moving focus to '%s' element", element) action_chains = ActionChains(driver) action_chains.move_to_element(page_element) action_chains.perform() with assertion_msg("Expected to see '%s' but can't see it", element): assert page_element.is_displayed()
def go_to_article(driver: webdriver, title: str): with selenium_action(driver, "Could not find article: %s", title): article = driver.find_element_by_link_text(title) if "firefox" not in driver.capabilities["browserName"].lower(): logging.debug("Moving focus to '%s' article link", title) action_chains = ActionChains(driver) action_chains.move_to_element(article) action_chains.perform() with assertion_msg( "Found a link to '%s' article but it's not visible", title): assert article.is_displayed() article.click() take_screenshot(driver, "After going to the '{}' Article".format(title))
def get_read_counter(driver: webdriver) -> int: with selenium_action(driver, "Could not find Article Read Counter"): counter = driver.find_element_by_css_selector(ARTICLES_TO_READ_COUNTER) if "firefox" not in driver.capabilities["browserName"].lower(): logging.debug("Moving focus to Article Read Counter") action_chains = ActionChains(driver) action_chains.move_to_element(counter) action_chains.perform() with assertion_msg("Article Read Counter is not visible"): assert counter.is_displayed() return int(counter.text)
def test_06_success(self, base_url, selenium): self.baseurl = base_url self.get(selenium, base_url + '/reconcile') src = selenium.find_element_by_id('ofx-2-OFX3') tgt = selenium.find_element_by_id( 'trans-3').find_element_by_class_name('reconcile-drop-target') # drag and drop chain = ActionChains(selenium) chain.drag_and_drop(src, tgt).perform() # ensure that the OFX div was hidden in the OFX column src = selenium.find_element_by_id('ofx-2-OFX3') assert src.is_displayed() is False # ensure that the OFX div was placed in the drop target tgt = selenium.find_element_by_id('trans-3') expected = txn_div( 3, date(2017, 4, 11), 600, 'BankTwo', 2, '2Periodic', 2, 'trans2', drop_div=ofx_div( date(2017, 4, 9), 600.00, 'BankTwo', 2, 'Purchase', 'OFX3', 'ofx3-trans2-st1', trans_id=3 ) ) assert self.normalize_html(tgt.get_attribute('outerHTML')) == expected # ensure the reconciled variable was updated assert self.get_reconciled(selenium) == { 3: [2, 'OFX3'] }
def __init__(self): self.cookies = None path = "C:\Program Files (x86)\Google\Chrome\chromedriver.exe" chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") self.driver = webdriver.Chrome(service_args=['--load-images=no'], executable_path=path, chrome_options=chrome_options) self.action = ActionChains(self.driver) self.retry_login()
def goto_profile_page(self): my = self.waitUntilFindElement(MainPageLocators.MY) account = self.waitUntilFindElement(MainPageLocators.ACCOUNT) actions = ActionChains(self.driver) actions.move_to_element(my).perform() actions.click(account).perform() # ActionChains(self.driver).move_to_element(my).click(account).perform()
def test_teacher_add_a_homework_using_the_calendar_date_8029(self): """Add a homework using the calendar date. Steps: Click on a date at least one day later than current date on calendar From the menu that appears, click on 'Add Homework' Expected Result: The teacher is taken to a page where they create the assignment. """ self.ps.test_updates['name'] = 't1.16.002' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.16', 't1.16.002', '8028'] self.ps.test_updates['passed'] = False # Test steps and verification assertions calendar_date = self.teacher.wait.until( expect.element_to_be_clickable( (By.XPATH, '//div[contains(@class,"Day--upcoming")]') ) ) self.teacher.driver.execute_script( 'return arguments[0].scrollIntoView();', calendar_date) self.teacher.driver.execute_script('window.scrollBy(0, -80);') self.teacher.sleep(2) actions = ActionChains(self.teacher.driver) actions.move_to_element(calendar_date) actions.move_by_offset(0, -35) actions.click() actions.move_by_offset(30, 45) actions.click() actions.perform() assert('homework/new' in self.teacher.current_url()),\ 'not at Add Homework page' self.ps.test_updates['passed'] = True # Case C8030 - 003 - Teacher | Set open/due dates for periods collectively
def test_teacher_add_event_using_the_calendar_date_8119(self): """Add an event using the calendar date. Steps: Click on a calendar date Click on the 'Add Event' option Expected Result: user taken to add ecent page with due date filled in """ self.ps.test_updates['name'] = 't1.21.003' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.21', 't1.21.003', '8119'] self.ps.test_updates['passed'] = False # Test steps and verification assertions calendar_date = self.teacher.wait.until( expect.element_to_be_clickable( (By.XPATH, '//div[contains(@class,"Day--upcoming")]') ) ) self.teacher.driver.execute_script( 'return arguments[0].scrollIntoView();', calendar_date) self.teacher.sleep(1) actions = ActionChains(self.teacher.driver) actions.move_to_element_with_offset(calendar_date, 50, 10) actions.click() actions.perform() self.teacher.find( By.XPATH, '//ul[@class="new-assignments"]//a[contains(text(),"Add Event")]' ).click() assert('event/new' in self.teacher.current_url()),\ 'not at Add Event page' self.ps.test_updates['passed'] = True # Case C8120 - 004 - Teacher | Set open and due dates for all periods # collectively
def test_teacher_add_an_event_by_dragging_add_event_to_a_cale_111249(self): """Add an event by dragging Add Event to a calendar date. Steps: Click on the 'Add Assignment' menu Click and Drag 'Add Event' to a chosen due date Expected Result: User is taken to 'Add Event' page with the date filled in. """ self.ps.test_updates['name'] = 't1.21.032' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.21', 't1.21.032', '111249'] self.ps.test_updates['passed'] = False # Test steps and verification assertions raise NotImplementedError(inspect.currentframe().f_code.co_name) # Assignment().open_assignment_menu(self.teacher.driver) # self.teacher.sleep(1) # calendar_date = self.teacher.wait.until( # expect.element_to_be_clickable( # (By.XPATH, '//div[contains(@class,"Day--upcoming")]') # ) # ) # add_event = self.teacher.find( # By.XPATH, # '//ul[@class="new-assignments"]//a[contains(text(),"Add Event")]' # ) # actions = ActionChains(self.teacher.driver) # actions.drag_and_drop(add_event, calendar_date) # actions.perform # self.teacher.sleep(4) # assert('event/new' in self.teacher.current_url()),\ # 'not at Add Event Assignment page' self.ps.test_updates['passed'] = True
def test_teacher_add_external_assignment_using_calendar_date_8086(self): """Add an external assignment using the calendar date. Steps: Click on a calendar date Click on the Add External Assignment option Expected Result: User taken to Add External Assignment page with due date filled in """ self.ps.test_updates['name'] = 't1.18.002' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.18', 't1.18.002', '8086'] self.ps.test_updates['passed'] = False # click on calendar date calendar_date = self.teacher.wait.until( expect.element_to_be_clickable( (By.XPATH, '//div[contains(@class,"Day--upcoming")]') ) ) self.teacher.driver.execute_script( 'return arguments[0].scrollIntoView();', calendar_date) self.teacher.sleep(1) actions = ActionChains(self.teacher.driver) actions.move_to_element(calendar_date) actions.move_by_offset(0, -35) actions.click() actions.move_by_offset(30, 70) actions.click() actions.perform() assert('external/new' in self.teacher.current_url()),\ 'not at Add External Assignment page' self.ps.test_updates['passed'] = True # Case C8087 - 003 - Teacher | Set open and due dates for all periods # collectively
def login( self, email, password ): self.browser.get( "http://mail.google.com" ) sleep( 3 ) self.action = webdriver.ActionChains( self.browser ) self.email_form = self.browser.find_element_by_id( "Email" ) self.email_form.send_keys( email ) self.next_button = self.browser.find_element_by_id( "next" ) self.next_button.click() sleep( 1 ) if not self.browser.find_element_by_id( "Passwd" ): self.printq.put( "[-] Invalid email, removing {} from scope".format( email ) ) self.emails.remove( email ) else: self.pass_form = self.browser.find_element_by_id( "Passwd" ) self.pass_form.send_keys( password ) self.signin_button = self.browser.find_element_by_id( "signIn" ) self.signin_button.click() sleep( 3 ) self.browser.save_screenshot( "{}_{}.png".format( email, password ) ) if "Wrong password" in self.browser.page_source: self.printq.put( "[!] Login failed: {}:{}".format( email, password ) ) else: self.printq.put( "[^] Login succeeded: {}:{}".format( email, password ) )
def fuck_verify_code(self): Bs = BeautifulSoup(self.browser.page_source,'lxml') # print(self.browser.page_source) try: try: Bfind = Bs.find('iframe')['src'] # ??????????url self.browser.get(Bfind) except TypeError: print("?????????????????,??????????????????Sorry~") except WebDriverException: print("?????????????????,??????????????????Sorry~") # self.reboot_verify_code() time.sleep(2) token_code = self.browser.find_element_by_xpath('//*[@id="token_code"]') btn = self.browser.find_element_by_xpath('//*[@id="scroller"]/div[2]/form/div[1]/button') verify_code = input("?????: ") # ????? verify_code_action = ActionChains(self.browser) verify_code_action.move_to_element(token_code).click().send_keys(verify_code) verify_code_action.move_to_element(btn).click() verify_code_action.perform() time.sleep(5) self.browser.save_screenshot('ceshi4.png') print("????!,????cookie....") cookie = {} for c in self.browser.get_cookies(): cookie[c['name']] = c['value'] self.sava_cookie(self.username,cookie) print("????!") uin = self.get_fristdotai_time(self.get_sid(self.browser.page_source))['loginuin'] qzonetoken = self.get_qzonetoken(self.getCookie(self.username)) gtk = self.get_gtk(self.getCookie(self.username)) firstrtime = self.get_fristdotai_time(self.get_sid(self.browser.page_source))['times'] self.get_dotai_sad(uin,qzonetoken,gtk,firstrtime) print("OVER") # ???????
def login(self): print("?????????....") u = self.browser.find_element_by_xpath('//*[@id="u"]') p = self.browser.find_element_by_xpath('//*[@id="p"]') go = self.browser.find_element_by_xpath('//*[@id="go"]') u.clear() # ?????????? action = ActionChains(self.browser) # ?????? action.move_to_element(u).click().send_keys(self.username) # ?????????????????? action.move_to_element(p).click().send_keys(self.password) # ?????????????????? action.move_by_offset(go.location['x'],go.location['y']) action.click(go) action.perform() time.sleep(3) self.browser.save_screenshot('ceshi1.png') if self.browser.title != "QQ??": print("????~") time.sleep(2) self.fuck_verify_code() else: print("????!,????cookie....") cookie = {} for c in self.browser.get_cookies(): cookie[c['name']] = c['value'] self.sava_cookie(self.username,cookie) print("????!") self.get_dotai_sad(self.get_fristdotai_time(self.get_sid(self.browser.page_source))['loginuin'],self.get_qzonetoken(self.getCookie(self.username)),self.get_gtk(self.getCookie(self.username)),self.get_fristdotai_time(self.get_sid(self.browser.page_source))['times']) print("OVER")
def Set(cls, value): if value == "": return if value == "SET_EMPTY": value = "" log.step_normal(u"Element [%s]: Set Value [%s]." % (cls.__name__, value)) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) if elements[cls.index].tag_name == "select" or elements[cls.index].tag_name == "ul": cls.Select(value) time.sleep(3) else: elements[cls.index].clear() action = webdriver.ActionChains(env.driver) action.send_keys_to_element(elements[cls.index], value) action.perform() time.sleep(3) cls.__clearup()
def movetoelement(cls): log.step_normal("Element [%s]: Do movetoelement()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) element = env.driver.find_element(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.move_to_element(element) action.perform() time.sleep(3)
def Right_Click(cls): log.step_normal("Element [%s]: Do Right_Click()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_element(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.context_click(elements).perform() time.sleep(3) cls.__clearup()
def Click_key_down_up(cls): log.step_normal("Element [%s]: Do Click_key_down_up()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_element(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.key_down(elements).key_up(elements) time.sleep(3) cls.__clearup() # APP?????????????
def ClickList(cls): log.step_normal("Element [%s]: Do ClickList()" % cls.__name__) if env.RUNNING_BROWSER in ("Chrome", "Firefox", "IE", "Safari"): js1 = "var q = document.documentElement.scrollTop=0" env.driver.execute_script(js1) time.sleep(3) js2 = "var q = document.documentElement.scrollTop=100000" env.driver.execute_script(js2) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) i = 0 while i < 1: elements = env.driver.find_elements(cls.by, cls.value) rd = random.randint(0, len(elements)-1) action = webdriver.ActionChains(env.driver) action.move_to_element(elements[rd]) action.click(elements[rd]) action.perform() time.sleep(2) i += 1 env.driver.switch_to_window(env.driver.window_handles[-1]) env.driver.maximize_window() time.sleep(3) cls.__clearup()
def ClickAndHold(cls): log.step_normal("Element [%s]: Do ClickAndHold()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.move_to_element(elements[cls.index]) action.click_and_hold(elements[cls.index]) action.perform() cls.__clearup()
def ReleaseClick(cls): log.step_normal("Element [%s]: Do ReleaseClick()" % cls.__name__) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.release(elements[cls.index]) action.perform() cls.__clearup()
def SendEnter(cls): log.step_normal(u"Element [%s]: SendEnter()" % (cls.__name__, )) # cls.__wait() WebDriverWait(env.driver, 10).until(lambda the_driver: the_driver.find_element(cls.by, cls.value).is_displayed()) elements = env.driver.find_elements(cls.by, cls.value) action = webdriver.ActionChains(env.driver) action.send_keys_to_element(elements[cls.index], Keys.ENTER) action.perform() cls.__clearup()