def instruct_menu_to_cohort_roster(driver, cohort="pt"): import time time.sleep(0.5) cohort_lead = driver.find_element_by_xpath( '/html/body/div[1]/nav/div[1]/ul/li[1]/a') my_cohorts = driver.find_element_by_xpath( '//*[@id="js-parentDropdownLink"]') if cohort == "pt": cohort_link = driver.find_element_by_xpath( '//*[@id="js-childrenList-141"]/ul/li[1]/a') elif cohort == "ft": cohort_link = driver.find_element_by_xpath( '//*[@id="js-sidenavChildrenList-140"]/li[2]/a') # return ft_cohort actions = ActionChains(driver) actions.move_to_element(cohort_lead) actions.pause(.5) actions.click(my_cohorts) actions.pause(.5) actions.click(cohort_link) return actions.perform()
def close_modal(driver): # Sometimes, a popup appears asking if we want to "Go Paperless". We # will wait 10 seconds for this popup to appear, closing it if it does. popup_wait = WebDriverWait(driver, 10) popup = None try: popup_wait.until( EC.visibility_of_element_located( (By.CSS_SELECTOR, 'div[id="paperlessModal"]'))) popup = driver.find_element_by_css_selector('div[id="paperlessModal"]') except: # noqa: E722 # If we can't find this popup, no worries log.info("no popup") pass # Close the popup if we found it if popup is not None: log.info("closing popup") close_button = popup.find_element_by_css_selector("button") # Pause after closing to make sure it disappears actions = ActionChains(driver) actions.click(close_button) actions.pause(5) actions.perform() try: driver.wait(5).until( EC.presence_of_element_located( (By.CSS_SELECTOR, ".modal-header button.close"))) driver.find_element_by_css_selector( ".modal-header button.close").click() except: # noqa: E722 # If we can't find this popup, no worries pass
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)
def move_mouse_to_volume_bar(self): """ Moves the mouse over to the volume bar. """ actions = ActionChains(self.SABL.ret_driver()) actions.move_to_element_with_offset(self.SABL.mute_button(), 60, 20) actions.pause(5) actions.perform()
def __clickOnPlaceholderNewMDOption(self): placeholderOpt = self._waitForClickableId( 'itemMachineDesignListForm:machineDesignAddOptions:0') action = ActionChains(self.driver) action.move_to_element(placeholderOpt) action.pause(0.5) action.click() action.release() action.perform()
def login(self): self.driver.get('https://ehire.51job.com/') js1 = "document.getElementsByClassName('headerBanner')[0].style.display='none'" js2 = "document.getElementsByClassName('topHeader')[0].style.display='none'" self.driver.execute_script(js1) self.driver.execute_script(js2) self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="txtMemberNameCN"]'))).send_keys( self.vipname) self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="txtUserNameCN"]'))).send_keys(self.username) self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="txtPasswordCN"]'))).send_keys(self.password) self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="btnBeginValidate"]'))).click() while True: time.sleep(1) imgelement = self.driver.find_element_by_xpath('//*[@id="divValidateHtml"]/div') # 定位验证码 self.driver.save_screenshot('aa.png') # 截取当前网页,该网页有我们需要的验证码 location = imgelement.location # 获取验证码x,y轴坐标 print(location) if location['x'] == 0: return size = imgelement.size # 获取验证码的长宽 print(size['width']) rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) # 写成我们需要截取的位置坐标 i = Image.open("aa.png") # 打开截图 frame4 = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域 frame4.save('frame4.png') chaojiying = Chaojiying_Client('jackie1102', 'salesmind1800', '9004') im = open('frame4.png', 'rb').read() while True: try: res = chaojiying.PostPic(im, 9004) except Exception as E: print(E) time.sleep(2) continue break content = res['pic_str'].split('|') loc_list = [] for i in content: loc = i.split(',') loc_list.append(loc) action = ActionChains(self.driver) for loca in loc_list: action.move_to_element_with_offset(imgelement, int(loca[0]), int(loca[1])).click() action.pause(1) action.perform() time.sleep(1) self.wait.until(EC.presence_of_element_located((By.LINK_TEXT, '验 证'))).click() time.sleep(1) success = self.driver.find_element_by_xpath('//*[@id="btnEndValidate"]').text if success == '验证通过': break else: chaojiying.ReportError(res['pic_id']) time.sleep(3) self.driver.find_element_by_xpath('//*[@id="Login_btnLoginCN"]').click()
def login(self, username, pw): #element=WebDriverWait(self.driver,30,0.5).until(EC.presence_of_element_located((By.XPATH,"//*[@id='x-URS-iframe']"))) #element = WebDriverWait(self.driver, 30, 0.5).until(EC.presence_of_element_located((By.XPATH, "//*[contains(@id,'x-URS-iframe')]"))) source_txt = self.driver.page_source html = etree.HTML(source_txt.encode()) frame_name = html.xpath( "//iframe[contains(@id,'x-URS-iframe')]/@id")[0] self.driver.find_element( By.XPATH, "//*[@id='switchAccountLogin']").click() ##需要先点击密码登陆 self.driver.switch_to.frame( frame_name) #此处用switch to frame,是由于嵌入的元素直接捕捉不到。 inputText = self.driver.find_element( By.XPATH, "//*[@id='account-box']//div[2]//input" ) ##--).click()点击失败,由于元素在xpath外面 inputText.send_keys(username) password = self.driver.find_element( By.XPATH, "//*[@id='login-form']//div//div[3]//div[2]//input[2]") password.send_keys(pw) password.send_keys(Keys.ENTER) time.sleep(0.5) #延迟移动鼠标,估计该element设置了延迟加载。 ele_che = self.driver.find_element(By.XPATH, "//*[@class='ScapTcha']") ##获取验证码元素 loca = ele_che.location #位置 action = ActionChains(self.driver) ##获取driver 事件操作。 action.move_to_element(ele_che).perform() #悬停在验证码触发框上 time.sleep(0.7) #延迟加载,不然yidun_tips__answer 还没渲染 ele_chi = self.driver.find_element( By.XPATH, "//*[@class='yidun_tips__answer']") ##获取汉字 ele_chi_list = re.split('\s+', ele_chi.text.replace('"', '')) time.sleep(0.2) #延迟,不然下列点击不生效 ele_chck_code_img = self.driver.find_element( By.XPATH, "//*[@class='yidun_panel']") #获取验证码图片 ele_chi_list_kev = {} i = 0 for it in ele_chi_list: ele_chi_list_kev[it] = [80 + i * 40, 40 + i * 40] i += 1 print(ele_chi_list_kev) for it in ele_chi_list: print(it) action.click(ele_chck_code_img) #<1>第一次点击,定位到该元素。 action.pause(2) #,链式操作该步骤延时2s action.move_to_element_with_offset(ele_chck_code_img, ele_chi_list_kev[it][0], ele_chi_list_kev[it][1]) #action.move_to_element_with_offset(ele_chck_code_img,80,40)#<2.0>移动元素,基于再次定位到ele_chck_code_img,去相对于其左上角位移80,40。 #action.move_by_offset(80,40)#<2.1>如果上步骤'<2.0>'换成本步骤'<2.1>',则是相对于'<1>' ('<1>'默认定位到元素中间)来说,往右下方移动80,40 action.click( ) #<3>:此时不能用<1>一样代码去触发点击事件,因为看其源码知道,如果传参数,则会初始化点击中间,不传参数,则点击当前鼠标位置。 action.perform() ##action 是一个链式操作,perform 是统一提交。
def hover_audit_log_download_and_check_tooltip(self): self.driver.minimize_window() link_element = self.find_element_by_locator((By.ID, 'export-audit-link')) hover = ActionChains(self.driver).move_to_element(link_element) hover.perform() hover.pause(3.0) self.wait_for_element_to_be_visible(Sitesettings_locators.audit_download_tooltip) tooltip = self.find_element_by_locator(Sitesettings_locators.audit_download_tooltip) self.validate_nested_element_text(tooltip, (By.CLASS_NAME, 'tooltip-header'), 'Export Audit Log') link_element.click()
def test_submitting_to_interviewdb(self): self.browser.get('https://www.interview-db.com/') if self.browser.find_element_by_link_text( 'Student Sign in with Github'): self.browser.find_element_by_link_text( 'Student Sign in with Github').click() self.browser.find_element_by_id('login_field').send_keys('Micjoey') self.browser.find_element_by_id('password').send_keys( 'v2CAMjBdOf1lQ09DoIXuQ') # self.browser.find_element_by_link_text('Sign in').click() self.browser.find_element_by_class_name('btn-block').click() WebDriverWait(self.browser, 10).until(EC.url_changes(self.browser)) self.browser.get('https://www.interview-db.com/') self.browser.find_element_by_id('react-tabs-2').click() if WebDriverWait(self.browser, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, 'btn'))): self.browser.find_elements_by_class_name('btn')[5].click() # find the Job Title input field title = self.browser.find_element_by_id( 'root_applications_0_jobTitle') title.click() title.send_keys('test') # # find the company field and create it or select actions = ActionChains(self.browser) companyButton = self.browser.find_elements_by_class_name( 'css-1hwfws3')[0] actions.click(companyButton) actions.send_keys('hello') actions.pause(2) actions.send_keys(Keys.UP) actions.send_keys(Keys.ENTER) actions.perform() # # find the source field and create or select sourceButton = self.browser.find_elements_by_class_name( 'css-1hwfws3')[1] actions.reset_actions() actions.click(sourceButton) actions.send_keys('hello2') actions.pause(2) actions.send_keys(Keys.UP) actions.send_keys(Keys.ENTER) actions.perform() # self.browser.find_element_by_id('daily-report-submit').click()
def test_switchwindows(self): self.driver.get('https://www.baidu.com/') self.driver.find_element_by_xpath('//*[@id="u1"]/a').click() self.driver.find_element_by_xpath( '//*[@id="passport-login-pop-dialog"]/div/div/div/div[3]/a').click( ) windows = self.driver.window_handles self.driver.switch_to.window(windows[1]) action = ActionChains(self.driver) #输入用户名 self.driver.find_element_by_name('userName').send_keys('4561') #输入手机号 ele = self.driver.find_element_by_xpath( '//*[@id="TANGRAM__PSP_4__phone"]') ele.send_keys('19092778754') #复制手机号框中的值 # action.move_to_element(ele).click() action.move_to_element(ele).key_down( Keys.COMMAND).send_keys('a').key_up(Keys.COMMAND) action.move_to_element(ele).key_down( Keys.COMMAND).send_keys('c').key_up(Keys.COMMAND) action.perform() action = ActionChains(self.driver) # ele=self.driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_4__phone"]') # ele.send_keys('19092778754') # ele.send_keys(Keys.COMMAND,'a') # ele.send_keys(Keys.COMMAND,'c') #输入密码框中的值 oele = self.driver.find_element_by_xpath( '//*[@id="TANGRAM__PSP_4__password"]') oele.send_keys('li123456') action.move_to_element(oele) action.pause(1) # action.send_keys(Keys.NULL).pause(1) action.move_to_element(oele).send_keys(Keys.BACKSPACE).pause(1) action.move_to_element(oele).send_keys('7').pause(1) action.move_to_element(oele).send_keys(Keys.TAB).key_down( Keys.COMMAND).send_keys('v').key_up(Keys.COMMAND) action.perform() ele2 = self.driver.find_element_by_id('TANGRAM__PSP_4__verifyCode') # 关闭当前窗口,返回原来窗口 # self.driver.close() print(ele2.get_attribute("value")) time.sleep(6)
def gen_actions_and_perform(driver, slider_selector, offset): action_chains = ActionChains(driver) moves = gen_smooth_array(offset) slider = driver.find_element_by_css_selector(slider_selector) action_chains.move_to_element_with_offset(slider, random.randint(5, 10), random.randint(2, 8)) action_chains.click_and_hold(slider).pause(0.05) last = 0 if random.random() > 0.5: direct = 1 else: direct = -1 for expect in moves: y = random.randint(1, 2) * direct offset = max(expect - last + random.randint(0, 2), 0) action_chains.move_by_offset(offset, y).pause(random.uniform(0.01, 0.02)) last += offset action_chains.pause(random.uniform(0.1, 0.2)).release(slider) action_chains.perform()
def drag_slider(self, source, gap): """ 模仿人的拖拽动作:快速沿着X轴拖动(存在误差),再暂停,然后修正误差 防止被检测为机器人,出现“图片被怪物吃掉了”等验证失败的情况 :param source:要拖拽的html元素 :param gap: 拖拽目标x轴距离 :return: None """ action_chains = ActionChains(self.browser) # 点击,准备拖拽 action_chains.click_and_hold(source) # 拖动次数,二到三次 dragCount = random.randint(2, 3) if dragCount == 2: # 总误差值 sumOffsetx = random.randint(-15, 15) action_chains.move_by_offset(gap + sumOffsetx, 0) # 暂停一会 action_chains.pause(self.get_random_seconds()) # 修正误差,防止被检测为机器人,出现图片被怪物吃掉了等验证失败的情况 action_chains.move_by_offset(-sumOffsetx, 0) elif dragCount == 3: # 总误差值 sumOffsetx = random.randint(-15, 15) action_chains.move_by_offset(gap + sumOffsetx, 0) # 暂停一会 action_chains.pause(self.get_random_seconds()) # 已修正误差的和 fixedOffsetX = 0 # 第一次修正误差 if sumOffsetx < 0: offsetx = random.randint(sumOffsetx, 0) else: offsetx = random.randint(0, sumOffsetx) fixedOffsetX += offsetx action_chains.move_by_offset(-offsetx, 0) action_chains.pause(self.get_random_seconds()) # 最后一次修正误差 action_chains.move_by_offset(-sumOffsetx + fixedOffsetX, 0) action_chains.pause(self.get_random_seconds()) else: raise Exception("莫不是系统出现了问题?!") # 参考action_chains.drag_and_drop_by_offset() action_chains.release().perform()
def goto_admin_configuration_localization(self): # self.browser.find_element(By.ID, 'menu_admin_viewAdminModule') # same as above admin_el = self.browser.find_element(*self.admin) user_man_el = self.browser.find_element(*self.user_management) conf_el = self.browser.find_element(*self.admin_configure) local_el = self.browser.find_element(*self.localization) action = ActionChains(self.browser) action.move_to_element(admin_el) action.pause(0.5) action.move_to_element(user_man_el) action.pause(1) action.move_to_element(conf_el) action.pause(0.25) action.click(local_el) # action.move_to_element(self.wait_for_el(self.admin)) # action.move_to_element(self.wait_for_el(self.user_management)) # action.move_to_element(self.wait_for_el(self.configure)) # action.click(self.wait_for_el(self.localization)) action.perform()
# -*- coding: utf-8 -*- __author__ = "苦叶子" from selenium import webdriver from selenium.webdriver import ActionChains if __name__ == "__main__": driver = webdriver.Chrome() action_chains = ActionChains(driver) driver.get("http://www.python.org") # 获取About链接元素,并加入动作链 About = driver.find_element_by_link_text("About") Events = driver.find_element_by_link_text("Events") action_chains.drag_and_drop(About, Events) action_chains.pause(2) # 执行动作链 action_chains.perform() driver.quit()
def do_login(self, u_name, u_pwd): # 为了防止你不确定自己的 chrom 版本,最好两个混合用 options = webdriver.ChromeOptions() # chrom在79版之前用这个 options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) # =>linux环境 为Chrome配置无头模式 # options.add_argument("--headless") # options.add_argument('--no-sandbox') # options.add_argument('--disable-gpu') # options.add_argument('--disable-dev-shm-usage') chrome = webdriver.Chrome(options=options) # 设置窗口最大化防止滑块拖动异常 chrome.maximize_window() # chrome.fullscreen_window() # chrom在79版之后用这个 chrome.execute_cdp_cmd( "Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) log.info('step-1 打开登录页...') chrome.get( 'https://login.taobao.com/member/login.jhtml?') # 发送请求,打开淘宝登录地址 log.info('sleep 2秒等待网页加载...') time.sleep(2) # 等待加载,网络不好的话页面信息加载不出来,可以根据网速自行设定 username_input = chrome.find_element_by_id("fm-login-id") # 获取用户名输入窗口 password_input = chrome.find_element_by_id( "fm-login-password") # 获取密码输入窗口 log.info('step-2 输入用户名密码...') username_input.send_keys(u_name) # 输入用户名 password_input.send_keys(u_pwd) # 输入密码 log.info('sleep 2秒等待加载滑块...') time.sleep(2) # 等待加载,这里会加载滑块 log.info('step-3 获取并拖动滑块...') try: slider = chrome.find_element_by_xpath( "//span[contains(@class, 'btn_slide')]") if slider.is_displayed(): action = ActionChains(chrome) # 创建动作链 action.click_and_hold(on_element=slider).perform() action.move_by_offset(xoffset=258, yoffset=0).perform() action.pause(0.5).release().perform() except: pass log.info('拖动滑块后等待js校验...') time.sleep(2) # login_button = chrome.find_element_by_xpath( # "/html/body/div/div[2]/div[3]/div/div[1]/div/div[2]/div/form/div[4]/button") # 获取登录按钮 # login_button.click() # 点击登录 chrome.find_element_by_xpath( '//*[@id="login-form"]/div[4]/button').click() log.info('step-4 点击登录,sleep 10s 环境检测...') # 等待登录检测和重定向 time.sleep(10) html = chrome.page_source # 获取登录后页面信息 # 重定向到指定url取接口相关token # html = chrome.get('http://....') # 等待页面加载 time.sleep(5) log.info('step-5 获取cookie...') cookie_str = self.get_cookies(chrome) # 关闭chromedriver chrome.close() return cookie_str
driver.get("https://www.w3schools.com/default.asp") """ image_2_drag = driver.find_element_by_xpath('//*[@id="drag1"]') element_2_put = driver.find_element_by_css_selector('#div2') actions = ActionChains(driver) actions.drag_and_drop(image_2_drag,element_2_put) actions.click(element_2_put) actions.release() actions.perform() actions.pause(2) """ menu = driver.find_element_by_xpath('//*[@id="navbtn_references"]') subMenu = driver.find_element_by_xpath('/html/body/nav[3]/div/div[1]/a[1]') actions = ActionChains(driver) actions.click(menu) actions.click(subMenu) actions.pause(4) actions.perform() driver.back() menu = driver.find_element_by_xpath('//*[@id="navbtn_references"]') menu.click() subMenu = driver.find_element_by_xpath('/html/body/nav[3]/div/div[1]/a[1]') subMenu.click() driver.quit()
def check_yzm(self): """ 验证码处理: 1·捕获验证码,对当前页面进行截屏 2·定位验证码图片位置,并从截屏中提取 3·调用打码平台,破解验证码,返回验证码参数 4·对验证码参数进一步处理,并模拟人工操作破解验证码 5·验证是否破解成功,否则发送验证失败api :return: """ while True: try: imgelement = self.driver.find_element_by_xpath('//*[@id="divValidateHtml"]/div') # 定位验证码 self.driver.save_screenshot('aa.png') # 截取当前网页,该网页有我们需要的验证码 location = imgelement.location # 获取验证码x,y轴坐标 if location['x'] == 0: return size = imgelement.size # 获取验证码的长宽 rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) # 写成我们需要截取的位置坐标 i = Image.open("aa.png") # 打开截图 frame4 = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域 frame4.save('frame4.png') chaojiying = Chaojiying_Client('jackie1102', 'salesmind1800', '9004') im = open('frame4.png', 'rb').read() while True: try: res = chaojiying.PostPic(im, 9004) except Exception as E: print(E) time.sleep(2) continue break content = res['pic_str'].split('|') print(res) loc_list = [] for i in content: loc = i.split(',') loc_list.append(loc) action = ActionChains(self.driver) for loca in loc_list: action.move_to_element_with_offset(imgelement, int(loca[0]), int(loca[1])).click() action.pause(1) action.perform() time.sleep(1) self.wait.until(EC.presence_of_element_located((By.LINK_TEXT, '验 证'))).click() time.sleep(1) self.driver.refresh() imgelement = self.driver.find_element_by_xpath('//*[@id="divValidateHtml"]/div') # 定位验证码 print(imgelement, '111111') self.driver.save_screenshot('d://aa.png') # 截取当前网页,该网页有我们需要的验证码 location = imgelement.location # 获取验证码x,y轴坐标 print(location) if location['x'] == 0: print('验证成功') else: print('验证失败') chaojiying.ReportError(res['pic_id']) time.sleep(3) except: print('没有出现验证码') break
self.css = css def __call__(self, driver): element = driver.find_element(*self.locator) if self.css in element.get_attribute("class"): return element else: return False options = webdriver.ChromeOptions() """browser window size""" options.add_argument("start-maximized") """path to profiles""" options.add_argument("user-data-dir=\\path\\to\\profile") """path to exetutable""" options.binary_location = "\\path\\Chrome.exe"; driver = webdriver.Chrome(executeble_path='C:\\Users\\WL\\PycharmProjects\\seleniumintro\\chromedriver', chrome_options=options) driver.get('https://www.google.de/') ac = ActionChains(driver) driver.find_element_by_id("gb_70").click() ac.click_and_hold(driver.find_element_by_class_name("RveJvd")) ac.pause(2) ac.move_to_element(driver.find_element_by_name("identifier")) ac.perform()