def type_location(self, country): self.current_location.click() AC(self.driver).send_keys(country).perform() time.sleep(.4) AC(self.driver).send_keys(Keys.ENTER).perform() time.sleep(.4) self.load_body()
def set_intensity(self, container, value): try: sliderEl = container.find_element_by_class_name('rc-slider-handle') except NoSuchElementException: print('SideEffectsForm: failed to load sliderEl') curValue = sliderEl.get_attribute('aria-valuenow') # Need to change intensity value? if value != curValue: xOffset = None # Every time offset doesn't work, increase by 5 and try again additionalOffset = 0 while str(curValue) != str(value) and additionalOffset < 50: # print('additionalOffset: ' + str(additionalOffset)) if curValue != 1: # reset to base position AC(self.driver).drag_and_drop_by_offset(sliderEl, -200, 0).perform() # Calculate offset # Note: monitor and window sizes affect this. if xOffset != None: # First offset wasn't correct. Increment amount of offset additionalOffset += 5 xOffset = 11 * (value - 1) + additionalOffset AC(self.driver).drag_and_drop_by_offset(sliderEl, xOffset, 0).perform() curValue = sliderEl.get_attribute('aria-valuenow')
def type_state(self, state): self.move_to_el(self.state_dd) time.sleep(1.4) # need decent wait before sending keys AC(self.driver).send_keys(state).perform() time.sleep(.4) AC(self.driver).send_keys(Keys.ENTER).perform() time.sleep(.4)
def search(keyword,last,once): #로그인 직후 나오는 경고창을 우회하기 위해, instagram 페이지를 다시 로드해준다. browser.get("https://www.instagram.com/") #해당 xpath를 가지는 검색창을 찾은 후에 search = browser.find_elements_by_xpath("//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/input") sleep(1) #검색어를 해당 위치에 전송한다. search[0].send_keys(keyword) #검색창의 검색 버튼을 찾아 눌러(click())해준다. button = browser.find_elements_by_xpath("//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/span") AC(browser).move_to_element(button[0]).click().perform() sleep(2) #검색버튼을 누르면 여러 검색 결과들이 리스트로 나오는데 for i in browser.find_elements_by_tag_name("div"): #검색 결과중 <#키워드>인 것을 찾으면 if i.text == "#"+str(keyword): print("true") #iteration을 계산해준다. ietration은 ("iteration 반복 횟수 * 한번에 긁어오는 post 수)로 해당 키워드의 전체 포스트수를 나누어, #최종적으로 iteration을 몇번 반복하는지 자동으로 계산해준다. iteration = round(int(i.find_element_by_xpath("..").find_elements_by_tag_name("span")[2].text.replace(",",""))/(last*once)) #해당 <키워드>를 클릭해준다. AC(browser).move_to_element(i).click().perform() break else : pass return iteration
def type_state(self,state): # move to input below state (so add button doesn't cover on mobile) AC(self.driver).move_to_element(self.postal_code_input).perform() self.state_dd.click() time.sleep(2) # need decent wait before sending keys AC(self.driver).send_keys(state).perform() time.sleep(1) AC(self.driver).send_keys(Keys.ENTER).perform() time.sleep(1)
def type_country(self, country): # probably won't work on mobile (keyboard not open) el = self.location if main.is_ios(): el = self.location.find_element_by_tag_name('button') el.click() AC(self.driver).send_keys(country).perform() time.sleep(.4) AC(self.driver).send_keys(Keys.ENTER).perform() time.sleep(.4)
def select_remove_new_status(self, new_status): self.remove_select.click() time.sleep(1) action = AC(self.driver) action.send_keys(new_status) action.send_keys(Keys.ENTER) action.perform()
def editTicket(): rs() if isElement("//div[@class='ticket']"): tickets = driver.find_elements_by_xpath("//div[@class='ticket']") ticket = random.choice(tickets) AC(driver).double_click(ticket).perform() wait()
def fail_return(current): for ax in browser.find_elements_by_tag_name("a"): if ax.find_element_by_xpath("..").find_element_by_xpath( "..").find_element_by_xpath("..").find_element_by_xpath( "..").find_element_by_xpath("..").tag_name == "article": tests = ax.get_attribute("href").split("/")[4] if current == tests: AC(browser).move_to_element(ax).click().perform()
def set_election(self, employer, amount): employer_row = self.get_employer_row(employer) if employer_row is not None: self.clear_pay_election(employer_row) # should still be focused if main.is_desktop(): AC(self.driver).send_keys(amount).perform() else: self.enter_currency(amount)
def submit(self, formInfo, tabName): # Loop through each section set in the info passed in for sectionIndex, section in enumerate(formInfo): print('answering section: ' + str(sectionIndex)) # set loadedSection to equal a specific section[i] from the form loaded loadedSection = self.loadedData[sectionIndex] # Loop through each question in the section for questionIndex, question in enumerate(section): print('answering question: ' + str(questionIndex)) # set loadedQuestion to equal a specific question[i] in a section[i] from the form loaded loadedQuestion = loadedSection[questionIndex] # question refers to each question passed in the formInfo secondaryInfo = question.get('secondary', None) # loadedQuestion refers to each question loaded from the form questionOptions = loadedQuestion.get('options', None) # the following 3 values are set to the actual element textarea = loadedQuestion.get('textInput', None) dropdowns = loadedQuestion.get('dropdowns', None) multipleDropdown = question.get('multiple_dropdown') if questionOptions: inputEl = questionOptions[question['option']] inputEl.click() if textarea: textarea.send_keys(question.get('textInput', None)) if dropdowns: if multipleDropdown: self.form.set_dropdown(dropdowns[0], question.get('multiple_dropdown', None)) AC(self.driver).send_keys(Keys.ESCAPE).perform() else: self.form.set_dropdown(dropdowns[0], question.get('dropdown', None)) if secondaryInfo: # Question has secondary response # Reload question and get loadedInfo for secondary question WDW(self.driver, 20).until(lambda x: self.load(tabName)) loadedSecondaryInfo = self.loadedData[sectionIndex][questionIndex].get('secondary_questions', None) secondaryText = secondaryInfo.get('text', None) secondaryOptions = secondaryInfo.get('options', None) if secondaryText: textInput = loadedSecondaryInfo[0]['textInput'] if textInput: textInput.clear() textInput.send_keys(secondaryText) else: print('could not find textarea for question[' + str(questionIndex) + ']') else: radioOptions = loadedSecondaryInfo[0]['options'] radioOptions[secondaryOptions].click() time.sleep(1) return True
def clear_pay_election(self, employer_row): # set focus and clear out existing election for given employer row el self.set_focus_on_employer(employer_row) amount = self.get_election_amount(employer_row) # desktop: hit backspace until input clear if main.is_desktop(): for i in xrange(len(amount)): AC(self.driver).send_keys(Keys.BACKSPACE).perform() else: # Mobile: hit backspace on custom keyboard self.clear_currency(amount)
def add_physician_typeahead(self, partial_name, full_name, physicianInfo): # Enter partial_name, select option w/ full_name, verify info matches physicianInfo # Enter partial_name physician_elements = self.physicians[-1]['elements'] physician_elements['name_input'].click() AC(self.driver).send_keys(partial_name).perform() # Wait for options to show up, then click option that matches full_name WDW(self.driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, 'rbt-menu'))) count = 0 loaded = False while not loaded or count > 10: count += 1 try: menu = self.driver.find_element_by_class_name('rbt-menu') options = menu.find_elements_by_tag_name('li') for option in options: option_text = option.text if option_text == 'No matches found.': time.sleep(.5) break elif option.text == full_name: anchor = option.find_element_by_tag_name('a') anchor.click() loaded = True except StaleElementReferenceException: pass # Reload to avoid staleElementException WDW(self.driver, 10).until(lambda x: self.load()) physician_elements = self.physicians[-1]['elements'] # Validate physicianInfo failures = [] if physicianInfo['name'] != physician_elements[ 'name_input'].get_attribute('value'): failures.append('Name does not match.') if physicianInfo['facility'] != physician_elements[ 'facility_input'].get_attribute('value'): failures.append('Facility does not match') if physicianInfo['city'] != physician_elements[ 'city_input'].get_attribute('value'): failures.append('City does not match') if physicianInfo['state'] != physician_elements['state_selector'].text: failures.append('State does not match') if len(failures) > 0: for failure in failures: print(failure) return False else: return True
def fail_return(current): #a를 태그로 갖는 모든 객체를 찾는다. for ax in browser.find_elements_by_tag_name("a"): #xpath(",,")는 윈도우의 상위 디렉토리 지정(cd ..)의 <..>와 같다. 즉 해당 태그에서 계속해서 상위 태그로 이동하여 # 4계단 위의 상위 태그가 "article"이라면 if ax.find_element_by_xpath("..").find_element_by_xpath("..").find_element_by_xpath("..").find_element_by_xpath("..").find_element_by_xpath("..").tag_name == "article": #해당 객체의 주소 "href"를 반환받는다. tests = ax.get_attribute("href").split("/")[4] #만일 현재 URL이 해당 객체의 "href"와 같다면 if current == tests: #그 객체를 클릭(click)한다. AC(browser).move_to_element(ax).click().perform()
def search(keyword, last, once): browser.get("https://www.instagram.com/") search = browser.find_elements_by_xpath( "//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/input") sleep(1) search[0].send_keys(keyword) button = browser.find_elements_by_xpath( "//*[@id='react-root']/section/nav/div[2]/div/div/div[2]/span") AC(browser).move_to_element(button[0]).click().perform() sleep(2) for i in browser.find_elements_by_tag_name("div"): if i.text == "#" + str(keyword): print("true") iteration = round( int( i.find_element_by_xpath("..").find_elements_by_tag_name( "span")[2].text.replace(",", "")) / (last * once)) AC(browser).move_to_element(i).click().perform() break else: pass return iteration
def set_physician(self, physicianInfo, index): p_elements = self.physicians[index]['elements'] if physicianInfo['name']: p_elements['name_input'].click() AC(self.driver).send_keys(physicianInfo['name']).perform() p_elements['facility_input'].clear() if physicianInfo['facility']: p_elements['facility_input'].send_keys(physicianInfo['facility']) p_elements['city_input'].clear() if physicianInfo['city']: p_elements['city_input'].send_keys(physicianInfo['city']) if physicianInfo['state']: self.set_physician_state(physicianInfo['state'], index)
def dragTicket(): rs() tickets = b.find_elements_by_css_selector("div.ticket") if len(tickets) < 1: return ticket = random.choice(tickets) board = b.find_element_by_css_selector("div#board") xdest = random.randint(0, board.size.get('width') - ticket.size.get('width')) ydest = random.randint( 0, board.size.get('height') - ticket.size.get('height')) AC(b).click_and_hold(ticket).move_to_element_with_offset( board, xdest, ydest).release(ticket).perform()
def login_seq(ids, passwords): try: browser.get( "https://www.instagram.com/accounts/login/?source=auth_switcher") login = browser.find_element_by_name("username") login.send_keys(ids) password = browser.find_element_by_name("password") password.send_keys(passwords) submit = browser.find_elements_by_xpath( "//*[@id='react-root']/section/main/div/article/div/div[1]/div/form/div[3]/button" ) AC(browser).move_to_element(submit[0]).click().perform() except: pass
def set_state(self, state_text): WDW(self.driver, 10).until( EC.presence_of_element_located( (By.CLASS_NAME, 'sm-state-menuitem'))) try: self.states = self.driver.find_elements_by_class_name( 'sm-state-menuitem') for i, state in enumerate(self.states): text = self.states[i].text if text == state_text: self.nav.click_el(self.states[i]) break except NoSuchElementException: # couldn't find state. De-select dropdown AC(self.driver).send_keys(Keys.ESC).perform() WDW(self.driver, 10).until_not( EC.presence_of_element_located( (By.CLASS_NAME, 'sm-state-menuitem')))
def moveTicket(): rs() tickets = driver.find_elements_by_xpath("//div[@class='ticket']") if len(tickets) < 1: return ticket = random.choice(tickets) board = driver.find_element_by_xpath("//div[@class='board']") xdest = random.randint(0, board.size.get('width') - ticket.size.get('width')) ydest = random.randint( 0, board.size.get('height') - ticket.size.get('height')) if xdest > 0 | ydest > 0: AC(driver).click_and_hold(ticket).move_to_element_with_offset( board, xdest, ydest).release(ticket).perform() wait()
def test_action_chains(self, cross_browser): driver = cross_browser[0] driver.get(TestRefreshers.website) actions = AC(driver) name_pair = TestRefreshers.hover_test driver.execute_script("window.scroll(0,1200)") actions.move_to_element(driver.find_element(*name_pair)) actions.move_to_element( driver.find_element(*TestRefreshers.hover_test_home)) actions.click() driver.execute_script("window.scroll(0,1200)") actions.move_to_element(driver.find_element(*name_pair)) actions.move_to_element( driver.find_element(*TestRefreshers.hover_test_reload)) actions.click() actions.perform() self.logger.info("Accomplished.. ActionChains rehearsal")
def clear_currency_input(self, currency_type): """Clear out amount of given currency_type""" # set focus on input el = None amount = '' if currency_type.lower() == 'usd': el = self.usd_amount amount = self.get_usd() elif currency_type.lower() == 'mxn': el = self.mxn_amount amount = self.get_mxn() el.click() # Desktop: hit backspace enough times to clear out current amount # Mobile: hit backspace (on custom keyboard) enough times to clear if main.is_desktop(): for i in xrange(len(amount)): AC(self.driver).send_keys(Keys.BACKSPACE).perform() else: # Mobile: hit backspace on custom keyboard self.clear_currency(amount)
def submit(self, physicianInfo, action='submit'): if physicianInfo: if physicianInfo['name']: self.name_input.click() AC(self.driver).send_keys(physicianInfo['name']).perform() if physicianInfo['facility']: self.facility_input.clear() self.facility_input.send_keys(physicianInfo['facility']) if physicianInfo['city']: self.city_input.clear() self.city_input.send_keys(physicianInfo['city']) if physicianInfo['state']: self.set_state(physicianInfo['state']) if action == 'submit': self.submit_button.click() elif action == 'cancel': self.cancel_button.click() elif action == 'close': self.close_button.click() return True return False
def login_seq(ids,passwords): try: #로그인 페이지로 바로 접속한다. browser.get("https://www.instagram.com/accounts/login/?source=auth_switcher") #username을 이름으로 가지는 객체를 찾은 후 login = browser.find_element_by_name("username") #입력받은 ids를 해당 객체에 전송(send_keys)한다. login.send_keys(ids) #password를 이름으로 가지는 객체를 찾은 후 password = browser.find_element_by_name("password") #password를 password 객체에 전송(send_keys)한다. password.send_keys(passwords) #확인 버튼을 찾은 후 이를 클릭(click())해준다. submit = browser.find_elements_by_xpath("//*[@id='react-root']/section/main/div/article/div/div[1]/div/form/div[3]/button") AC(browser).move_to_element(submit[0]).click().perform() #예외가 발생할경우. 즉 이미 로그인이 되어있는 상태라면 이 시퀀스를 건너 뛰어준다. except: pass
def engine(firstpage, lastpage, current, post): datalist = [] kill_switch = 0 log = list() while firstpage <= lastpage: sleep(random.randint(0, 1)) #kill_switch = 0, 즉 예외가 발생했던 적이 없는 경우 try: fail_return(current) log.append("소생 페이즈 성공") for i in range(0, post): if i < (post - 2): log.append("start," + str(i)) j = len( browser.find_elements_by_xpath( "/html/body/div[3]/div/div[1]/div/div/a")) for k in browser.find_elements_by_xpath( "/html/body/div[3]/div/div[1]/div/div/a"): #만일 이전, 다음 버튼 두개가 존재하는 경우 if j == 2: if k.text == "다음": sleep(1) ab = browser.find_element_by_xpath( "/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span" ) datalist.append( ab.text.replace("\n", "").replace("#", " ")) log.append("append type1 완료") AC(browser).move_to_element( k).click().perform() current = browser.current_url.split("/")[4] #만일 이전, 다음 버튼 중 하나만 존재하는 경우 if j == 1: #다음 버튼만 존재하는 경우 : 첫 페이지를 의미 if k.text == "다음": sleep(1) ab = browser.find_element_by_xpath( "/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span" ) datalist.append( ab.text.replace("\n", "").replace("#", " ")) log.append("append type2 완료") AC(browser).move_to_element( k).click().perform() current = browser.current_url.split("/")[4] #이전 버튼만 존재하는 경우 : 마지막 페이지를 의미 else: sleep(1) ab = browser.find_element_by_xpath( "/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span" ) datalist.append( ab.text.replace("\n", "").replace("#", " ")) log.append("append type3 완료") exit = browser.find_element_by_xpath( "/html/body/div[3]/div/button") AC(browser).move_to_element( exit).click().perform() current = browser.current_url.split("/")[4] if i >= (post - 1): log.append("end," + str(i)) log.append("종료 페이즈 시작") exit = browser.find_element_by_xpath( "/html/body/div[3]/div/button") AC(browser).move_to_element(exit).click().perform() AC(browser).send_keys(Keys.PAGE_DOWN).perform() firstpage += 1 break #예외가 발생하면 일단 창의 X버튼을 누르고, kill_switch를 1로 켠다. except: try: exit = browser.find_element_by_xpath( "/html/body/div[3]/div/button") AC(browser).move_to_element(exit).click().perform() except: AC(browser).send_keys(Keys.PAGE_DOWN).perform() pass log.append("오류 발생") sleep(1) return (datalist, current, log)
def type_state(self, state): self.state.click() AC(self.driver).send_keys(state).perform() time.sleep(.4) AC(self.driver).send_keys(Keys.ENTER).perform() time.sleep(.4)
def close_find_atm(self): if main.is_desktop(): AC(self.driver).send_keys(Keys.ESCAPE).perform() else: self.atm_locator.send_keys(Keys.ESCAPE)
def _getinfo(self, webelement): AC(self.driver).move_to_element(webelement).perform() return self.driver.find_element_by_xpath( '//span[@id="fusioncharts-tooltip-element"]').text
def engine(firstpage,lastpage,current,post): datalist = [] kill_switch = 0 log = list() #while의 조건문은 iteration의 수다. 만일 1 <= 5 라면, 한번에 10개씩의 포스트를 긁어오는 작업을 5번 반복한다. while firstpage <= lastpage: sleep(random.randint(0,1)) #kill_switch = 0, 즉 예외가 발생했던 적이 없는 경우 try : #앞서 정의한 fail_return을 통해 저장된 현재 위치(current)를 다시 소생시킨다. fail_return(current) log.append("소생 페이즈 성공") #post는 한번에 긁어올 포스트의 수이다. for i in range(0,post): #i가 아직 포스트 수에 미치지 못했다면 if i < (post-2): #로그를 저장한다. log.append("start,"+str(i)) #<이전> 버튼과 <다음>버튼의 갯수 정보를 j에 담는다. 버튼이 둘 다 있을경우엔 2이고, 아닐 경우엔 1로 반환된다.. j = len(browser.find_elements_by_xpath("/html/body/div[3]/div/div[1]/div/div/a")) #<이전>버튼과 <다음>버튼을 for문으로 번갈아 가져온다. for k in browser.find_elements_by_xpath("/html/body/div[3]/div/div[1]/div/div/a"): #만일 이전, 다음 버튼 두개가 존재하는 경우 if j == 2: #그러면서, 동시에 그 버튼의 text 정보가 "다음"일 경우엔 if k.text == "다음" : sleep(1) #다음 버튼을 누르기 전에, 해당 포스트 내용을 긁어서 datalist에 저장한다. ab = browser.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span") datalist.append(ab.text.replace("\n","").replace("#"," ")) #이후 다음버튼(k)를 누른다. log.append("append type1 완료") AC(browser).move_to_element(k).click().perform() #해당 포스트 load에 실패할 경우를 대비하여, 다음 포스트의 URL정보를 current에 저장한다.(fail_return에 활용) current = browser.current_url.split("/")[4] #만일 이전, 다음 버튼 중 하나만 존재하는 경우 if j == 1: #다음 버튼만 존재하는 경우 : 첫 페이지를 의미 if k.text == "다음": sleep(1) ab = browser.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span") datalist.append(ab.text.replace("\n","").replace("#"," ")) log.append("append type2 완료") AC(browser).move_to_element(k).click().perform() current = browser.current_url.split("/")[4] #이전 버튼만 존재하는 경우 : 마지막 페이지를 의미 else : sleep(1) #다음 버튼을 누르기 전에, 해당 포스트 내용을 긁어서 datalist에 저장한다. ab = browser.find_element_by_xpath("/html/body/div[3]/div/div[2]/div/article/div[2]/div[1]/ul/li[1]/div/div/div/span") datalist.append(ab.text.replace("\n","").replace("#"," ")) #이후 다음버튼(k)를 누른다. log.append("append type3 완료") exit = browser.find_element_by_xpath("/html/body/div[3]/div/button") #exit 버튼의 위치를 find_element로 찾는다. AC(browser).move_to_element(exit).click().perform() #exit 버튼을 눌러 창을 닫는다. current = browser.current_url.split("/")[4] if i >= (post-1): #마지막으로 긁은 포스트의 순서를 log파일에 저장한다. log.append("end,"+str(i)) log.append("종료 페이즈 시작") #exit 버튼을 찾는다. exit = browser.find_element_by_xpath("/html/body/div[3]/div/button") #exit 버튼을 눌러 창을 찾는다. AC(browser).move_to_element(exit).click().perform() #Page_Down 키를 브라우저에 전송해서, 앞으로 긁어올 포스트의 위치에 스크롤을 맞춘다. ## 이는 Fail_return 상황이 발생할 경우, JAVA 기반의 인스타그램에서 해당 객체의 위치를 찾기 위해 스크롤이 해당 객체의 위치를 ## 불러서 저장해둘 필요가 있기 때문이다. AC(browser).send_keys(Keys.PAGE_DOWN).perform() firstpage += 1 break #예외가 발생하면 일단 창의 X버튼을 누르고, kill_switch를 1로 켠다. #예외가 발생하면 일단 창의 X버튼을 누른다. except : try: #exit 버튼을 찾아서 누른다. exit = browser.find_element_by_xpath("/html/body/div[3]/div/button") AC(browser).move_to_element(exit).click().perform() except : #만일 fail_return이 실패했을 경우엔 exit 버튼을 찾을 수 없다. exit 버튼을 찾지 못해 오류가 발생했을 경우 # page_down 키를 send 하여 fail_return이 해당 current를 찾도록 한다. AC(browser).send_keys(Keys.PAGE_DOWN).perform() pass log.append("오류 발생") sleep(1) return(datalist,current,log)
def createTicket(): rs() board = driver.find_element_by_xpath("//div[@class='board']") AC(driver).double_click(board).perform() wait()