def getCommunityTabSource(self): try: # 커뮤니티탭 소스 가져오기 self.driver.get(self.communityTab) wait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) try: tab_selector = '#tabsContent > paper-tab.style-scope.ytd-c4-tabbed-header-renderer.iron-selected:nth-of-type(4)' if re.compile('커뮤니티').search( self.driver.find_element_by_css_selector(tab_selector + ' > div').text ) and self.driver.find_element_by_css_selector( tab_selector).get_attribute('aria-selected'): self.scrollDown() self.communityTab_src = self.driver.page_source self.communityTab_parser = BeautifulSoup( self.communityTab_src, 'html.parser') self.communityTab_enable = True self.post_cnt = len( self.communityTab_parser.select( '#contents > ytd-backstage-post-thread-renderer')) elif self.driver.find_element_by_css_selector( tab_selector + ' > div' ).text == '홈' and self.driver.find_element_by_css_selector( tab_selector).get_attribute('aria-selected'): self.communityTab_enable = False self.post_cnt = 0 except NoSuchElementException: self.communityTab_enable = False self.post_cnt = 0 except Exception as e: print(pcolors.EXPT + self.channel_title + ', getCommunityTabSource(), ' + str(e) + pcolors.END)
def is_element_exist(self, b, path): try: wait(self.driver, self.timeout). \ until(conditions.visibility_of_element_located((self.by[b], path))) except exceptions.TimeoutException: return False return True
def getDiscussionTabSource(self): try: # 토론탭 소스 가져오기 self.driver.get(self.discussionTab) wait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) try: # 홈으로 넘어가는 경우 고려 tab_selector = '#tabsContent > paper-tab.style-scope.ytd-c4-tabbed-header-renderer.iron-selected:nth-of-type(5)' if re.compile('토론').search( self.driver.find_element_by_css_selector(tab_selector + ' > div').text ) and self.driver.find_element_by_css_selector( tab_selector).get_attribute('aria-selected'): self.scrollDown() self.discussionTab_src = self.driver.page_source self.discussionTab_parser = BeautifulSoup( self.discussionTab_src, 'html.parser') self.discussionTab_enable = True self.discussion_cnt = int( self.discussionTab_parser.select_one( '#count > yt-formatted-string').text[3:-1]) elif self.driver.find_element_by_css_selector( tab_selector + ' > div' ).text == '홈' and self.driver.find_element_by_css_selector( tab_selector).get_attribute('aria-selected'): self.discussionTab_enable = False self.discussion_cnt = 0 except NoSuchElementException: self.discussionTab_enable = False self.discussion_cnt = 0 except Exception as e: print(pcolors.EXPT + self.channel_title + ', getDiscussionTabSource(), ' + str(e) + pcolors.END)
def is_login_failed(self): try: wait(self.driver, self.timeout).\ until(lambda x: x.find_element_by_xpath("//div[contains(@title,'帐号或密码错误')]")) except exceptions.TimeoutException: return False return True
def test_resume_create(app): wd = app.wd app.open_page("login") time.sleep(5) app.login(username="******", password="******") wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//span[.='Создать резюме']")) wd.find_element_by_xpath("//span[.='Создать резюме']").click() wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//input[@id='Resume_post']")) # вводим данные в форму резюме wd.find_element_by_xpath("//span[.='Параметры']").click() wd.find_element_by_xpath("//input[@id='Resume_post']").send_keys("Тестовая должность") wd.find_element_by_xpath("//label[.='Администрация']").click() wd.find_element_by_xpath("//div[@id='s2id_autogen1']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Администратор']").click() wd.find_element_by_xpath("//div[@id='s2id_autogen3']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Свободный график']").click() wd.find_element_by_xpath("//dl[@class='accordion']//dt[4]").click() wd.find_element_by_xpath("//div[@id='s2id_autogen7']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Высшее']").click() wd.find_element_by_xpath("//input[@name='publish']").click() time.sleep(5) # даем возможность отправиться данным на сервер, без этого ожидания фэйлится app.open_page("resume") # проверяем публикацию резюме assert "Тестовая должность" == wd.find_element_by_xpath("//div[@class='items']/div[1]//a").text app.open_page("profile") # восстанавливаем начальное состояние wd.find_element_by_xpath("//a[@href='/job/resume/delete' and .='Удалить']").click() time.sleep(5)
def test_resume_save_then_publish(app): wd = app.wd app.session.login_as(app.users["user1"]) wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//span[.='Создать резюме']")) wd.find_element_by_xpath("//span[.='Создать резюме']").click() wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//input[@id='Resume_post']")) # вводим данные в форму резюме wd.find_element_by_xpath("//span[.='Параметры']").click() wd.find_element_by_xpath("//input[@id='Resume_post']").send_keys("Тестовая должность") wd.find_element_by_xpath("//label[.='Администрация']").click() wd.find_element_by_xpath("//div[@id='s2id_autogen1']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Администратор']").click() wd.find_element_by_xpath("//div[@id='s2id_autogen3']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Свободный график']").click() wd.find_element_by_xpath("//dl[@class='accordion']//dt[4]").click() wd.find_element_by_xpath("//div[@id='s2id_autogen7']//span[@class='select2-chosen']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Высшее']").click() wd.find_element_by_xpath("//input[@name='save']").click() time.sleep(5) # даем возможность отправиться данным на сервер, без этого ожидания фэйлится app.open_page("resume") # проверяем, что вакансия НЕ опубликована assert "Тест создания вакансии" != wd.find_element_by_xpath("//div[@class='items']/div[1]//a").text app.open_page("profile") # публикуем wd.find_element_by_xpath("//div[@class='user-inf__resume line']//a[.='Опубликовать']").click() time.sleep(5) app.open_page("resume") # проверяем, что вакансия успешно опубликована assert "Тестовая должность" == wd.find_element_by_xpath("//div[@class='items']/div[1]//a").text app.open_page("profile") # восстанавливаем начальное состояние wd.find_element_by_xpath("//div[@class='user-inf__resume line']//a[.='Удалить']").click() time.sleep(5)
def test_users_profile_could_be_opened_from_community(self): success = True wd = self.wd wd.get(str(Baseurl.baseurl) + "community") wd.find_element_by_link_text("Виктория Черепанова").click() wait(wd, 10).until(lambda s: wd.current_url == str(Baseurl.baseurl) + "user/1849") self.assertTrue(success)
def __init__(self, firstName, lastName, email, password): self.firstName = firstName self.lastName = lastName self.email = email self.password = password #create a new webdriver with a header options = webdriver.ChromeOptions() options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_argument('--ignore-certificate-errors') options.add_argument('--incognito') #remove headless option if you want to see the program work live #options.add_argument('--headless') options.add_argument( 'user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"' ) self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) #used to manage header requests self.driver.request_interceptor = interceptor curURL = self.driver.current_url self.driver.get("http://localhost:3000") wait(self.driver, 15).until(EC.url_changes(curURL)) self.driver.maximize_window() self.register() self.login()
def find(self, query): wd = self.app.wd self.app.open_companies_page() old_companies = wait(wd, 10).until(lambda s: wd.find_elements_by_css_selector("div#companiesList div.items div.line")) self.app.type_into(wd.find_element_by_id("keywords"), query) wd.find_element_by_id("filter-by-keywords").click() if len(old_companies) > 0: wait(wd, 10).until(ec.staleness_of(old_companies[0]))
def login(self): curURL = self.driver.current_url self.driver.find_element_by_xpath('//a[@href="' + "login/login.html" + '"]').click() wait(self.driver, 15).until(EC.url_changes(curURL)) self.driver.find_element_by_id("email").send_keys(self.email) self.driver.find_element_by_id("pass1").send_keys(self.password) assert (self.driver.find_element_by_id("submit_reg").is_enabled()) self.driver.find_element_by_id("submit_reg").click()
def test_users_profile_is_visible_from_event(self): success = True wd = self.wd wd.get(str(Baseurl.baseurl) + "events") wd.find_element_by_css_selector("div.event__ttl > a").click() time.sleep(2) wd.find_element_by_css_selector("a.post__list-person").click() wait(wd, 10).until(lambda s: str(Baseurl.baseurl) + "user/" in wd.current_url) self.assertTrue(success)
def test_articles_comment(app): wd = app.wd app.session.login_as(app.users["user1"]) app.open_page("article/article4029-pravila-hudozhnika-po-grimu-marii-morzunovoj") unique_comment = "comment" + strftime("%H:%M:%S", gmtime()) # генерируем уникальный коммент wait(wd, 60).until(lambda s: wd.find_element_by_id("Comment_comment_text")).send_keys(unique_comment) wait(wd, 60).until(lambda s: wd.find_element_by_link_text("Отправить")).click() time.sleep(3) assert unique_comment in wd.find_element_by_tag_name("body").text
def test_events_dropdown_navigation(app, locator, url): wd = app.wd actions = ActionChains(wd) wd.get(str(Baseurl.baseurl)) menu = wd.find_element_by_xpath("//ul[@id='main-menu']//a[.='События']") actions.move_to_element(menu).perform() wait(wd, 10).until(lambda s: wd.find_element_by_xpath(str(locator))) wd.find_element_by_xpath(str(locator)).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1")) assert wd.current_url == str(Baseurl.baseurl) + url
def test_articles_dropdown_navigation(app, locator, url): wd = app.wd actions = ActionChains(wd) app.open_page("") # home page time.sleep(2) menu = wd.find_element_by_xpath("//ul[@id='main-menu']//a[.='Статьи']") actions.move_to_element(menu).perform() wait(wd, 10).until(lambda s: wd.find_element_by_xpath(str(locator))) wd.find_element_by_xpath(str(locator)).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1")) assert wd.current_url == app.base_url + url
def test_pavillions_list_displayed_properly(app): wd = app.wd app.open_page("pavilions?town=1") assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@data-value='1']")).is_displayed() # теги с назначением павильона assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@data-value='2']")).is_displayed() assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@data-value='3']")).is_displayed() assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@data-value='4']")).is_displayed() assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@class='map-pin']/sup")).is_displayed() # геотег assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[@class='pavilion-image fancybox']/img")).is_displayed() # фото assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h2[@class='pavilion-name']/a")).is_displayed() # название павильона assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='pavilion-info line']/ul/li/strong")).is_displayed() # название компании, нет атрибутов чтобы обратиться иначе assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='pavilion-info line']/ul/li/i[@class='ico ico_place']")).is_displayed() # указание города assert wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='pavilion-info line']/ul/li[@class='price']/a")).is_displayed() # ссылка на запрос стоимости
def login(driver): url = 'https://weixin.sogou.com/' driver.get(url) time.sleep(3) driver.maximize_window() # 最大化窗口 driver.find_element_by_id('loginBtn').click() # 点击登录按钮 now = datetime.datetime.now().replace(microsecond=0) print(f'{now} --- 正在登录') time.sleep(3) wait(driver, 60).until_not( lambda x: x.find_element_by_class_name('qrcode lightBorder')) now1 = datetime.datetime.now().replace(microsecond=0) print(f'{now1} --- 登录成功~') time.sleep(3)
def test_user_can_send_request_for_placing_pavillion(app): wd = app.wd app.session.login_as(app.users["user2"]) app.open_page("pavilions?town=1") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Разместить павильон']")).click() time.sleep(5) wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Размещение павильонов']")) assert "Если вы предоставляете в аренду павильоны для кино-, теле-, видео-, или фотосъемки, вы можете опубликовать на нашем сайте информацию о ваших услугах." in wd.find_element_by_tag_name("body").text wait(wd, 10).until(lambda s: wd.find_element_by_id("open-popup")).click() wait(wd, 10).until(lambda s: wd.find_element_by_id("PavilionRequest_phone")).send_keys("+7(495) 123-456") wd.find_element_by_xpath("//div[@class='ui-dialog-buttonset']/button[1]").click() wait(wd, 10).until(lambda s: wd.find_element_by_id("request-success")) wd.find_element_by_xpath("//div[@class='ui-dialog-buttonset']/button").click() # потом добавить проверку текста письма в админке
def test_authorized_user_can_watch_profiles(app): wd = app.wd app.session.login_as(app.users["user1"]) app.open_page("user/1849") wd.find_element_by_link_text("Фотографии").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Фотографии']")) wd.find_element_by_xpath("//ul[@id='yw1']//strong[.=' Видео']").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Видео']")) wd.find_element_by_xpath("//ul[@id='yw1']//strong[.=' Мероприятия']").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Мероприятия']")) wd.find_element_by_xpath("//ul[@id='yw1']//strong[.=' Друзья']").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Друзья']")) wd.find_element_by_xpath("//ul[@id='yw1']//strong[.=' Сообщества']").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[.='Подписки']"))
def login_as(self, user): wd = self.app.wd if self.is_logged_in(): if self.is_logged_in_as(user): return else: self.logout() wd.get(self.app.base_url + "login") wait(wd, 10).until(lambda s: wd.find_element_by_id('UserForm_email')) wd.find_element_by_id('UserForm_email').send_keys(user.username) wd.find_element_by_id('UserForm_password').send_keys(user.password) wd.find_element_by_id('submit_link').click() wait(wd, 10).until(lambda s: self.is_logged_in())
def scrollDown(self): last_height = self.driver.execute_script( "return document.documentElement.scrollHeight") while True: self.driver.execute_script( "window.scrollTo(0, document.documentElement.scrollHeight);") try: wait(self.driver, 3).until(lambda driver: driver.execute_script( "return document.documentElement.scrollHeight") > last_height) except TimeoutException: break last_height = self.driver.execute_script( "return document.documentElement.scrollHeight")
def getPlaylistsTabSource(self): try: # 재생목록탭 소스 가져오기 self.driver.get(self.playlistsTab) wait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) self.scrollDown() self.playlistsTab_src = self.driver.page_source self.playlistsTab_parser = BeautifulSoup(self.playlistsTab_src, 'html.parser') self.playlists_cnt = len( self.playlistsTab_parser.select( '#items > ytd-grid-playlist-renderer')) except Exception as e: print(pcolors.EXPT + self.channel_title + ', getPlaylistsTabSource(), ' + str(e) + pcolors.END)
def login(self, account, pasword): try: wait(self.driver, 10). \ until(conditions.frame_to_be_available_and_switch_to_it((p.get(s, "login_frame_by"), p.get(s, "login_frame_path")))) except exceptions.TimeoutException as t: print('error: found timeout!切换frame失败') email = self.find_element(self.by[p.get(s, "email_input_by")], p.get(s, "email_input_path")) email.clear() email.send_keys(account) password = self.find_element(self.by[p.get(s, "password_input_by")], p.get(s, "password_input_path")) password.clear() password.send_keys(pasword) self.find_element(self.by[p.get(s, "login_button_by")], p.get(s, "login_button_path")).click()
def find_element(self, by, path): try: element = wait( self.driver, self.timeout).until(lambda x: x.find_element(by, path)) except exceptions.TimeoutException as t: print(t) else: return element
def test_rent_sale_filters(self): success = True wd = self.wd wd.get(str(Baseurl.baseurl) + "catalog/video_13/videokameri-i-kamkorderi_128/") wd.find_element_by_xpath("//label[.='Только аренда']").click() if wd.current_url != str(Baseurl.baseurl) + "catalog/video_13/videokameri-i-kamkorderi_128/?offerType=rent": success = False print("verifyCurrentUrl failed") wait(wd, 10).until(lambda s: "Средняя цена аренды" in wd.find_element_by_xpath("//div[@class='reviews__price']").text) wd.find_element_by_xpath("//label[.='Только продажа']").click() if wd.current_url != str(Baseurl.baseurl) + "catalog/video_13/videokameri-i-kamkorderi_128/?offerType=sale": success = False print("verifyCurrentUrl failed") wait(wd, 10).until(lambda s: "Средняя цена продажи" in wd.find_element_by_xpath("//div[@class='reviews__price']").text) wd.find_element_by_xpath("//label[.='Весь каталог']").click() if wd.current_url != str(Baseurl.baseurl) + "catalog/video_13/videokameri-i-kamkorderi_128/": success = False print("verifyCurrentUrl failed") self.assertTrue(success)
def test_authorized_user_can_watch_groups(app): wd = app.wd app.session.login_as(app.users["user1"]) app.open_page("group/253/members") wd.find_element_by_link_text("Фотографии").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Фотографии']")) wd.find_element_by_link_text("Участники").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Участники']")) wd.find_element_by_link_text("Видео").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1[.='Видео']")) wd.find_element_by_link_text("Лента").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//a[.='Сообщение']"))
def getHomeSource(self): try: # 홈 소스 가져오기 self.driver.get(self.home) wait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) self.scrollDown() self.home_src = self.driver.page_source self.home_parser = BeautifulSoup(self.home_src, 'html.parser') # 섹션 개수, 메인비디오 사용여부 가져오기 if self.home_parser.select_one( 'ytd-channel-video-player-renderer') is None: self.section_cnt = len( self.home_parser.select('#image-container')) else: self.main_video_enable = True self.section_cnt = len( self.home_parser.select('#image-container')) + 1 except Exception as e: print(pcolors.EXPT + self.channel_title + ', getHomeSource(), ' + str(e) + pcolors.END)
def wechat(): print('正在启动浏览器~ 骚等~') # 启动浏览器 driver = webdriver.Chrome() # 打开微信公众号地址 driver.get('https://mp.weixin.qq.com/') # 最大化窗口 driver.maximize_window() # 清空输入框内容并输入用户名 driver.find_element_by_name('account').clear() driver.find_element_by_name('account').send_keys(account) # 清空输入框内容并输入密码 driver.find_element_by_name('password').clear() driver.find_element_by_name('password').send_keys(password) # 点击 记住我 复选框 driver.find_element_by_class_name('icon_checkbox').click() # 强制休眠5s,以防太快输入被屏蔽 time.sleep(5) # 点击登录按钮 driver.find_element_by_class_name('btn_login').click() # 强制休息5s,用来扫描二维码? print('准备拿出手机扫描二维码了吗?') # time.sleep() # 检查是否登录成功 wait(driver, 20).until(lambda x: x.find_element_by_class_name( 'weui-desktop-operation-group_default')) print('登录成功了呢~') time.sleep(5) # 获取登录成功的cookies cookies = driver.get_cookies() print(cookies) post = {} # 获取到的cookies是列表形式,将cookies转换成json形式并存入本地文件中 for cookie in cookies: post[cookie['name']] = cookie['value'] cookie_str = json.dumps(post) with open('cookie.txt', 'w+') as f: f.write(cookie_str) print('cookie信息以保存到本地!') return driver
def loginProcesser(self) -> bool: self.wd.get('http://jksb.zzu.edu.cn/') self.wd.switch_to.frame(0) wait(self.wd, 30).until(ec.presence_of_element_located( (By.NAME, 'uid'))).send_keys(self.uid) wait(self.wd, 10).until(ec.presence_of_element_located( (By.NAME, 'upw'))).send_keys(self.pwd) wait(self.wd, 10).until(ec.element_to_be_clickable( (By.NAME, 'smbtn'))).submit() time.sleep(3) self.wd.switch_to.frame('zzj_top_6s') if '今日您已经填报过了' in self.wd.page_source: message = '{} 已经上报过了'.format( time.strftime('%Y-%m-%d %H : %M: %S', time.localtime(time.time() + 8 * 3600))) print(message) Wechat('上报过了', message) return True wait(self.wd, 10).until( ec.element_to_be_clickable( (By.XPATH, "//span[contains(.,\'本人填报\')]"))).click() wait(self.wd, 10).until( ec.element_to_be_clickable( (By.XPATH, "//span[contains(.,\'提交表格\')]"))).click() time.sleep(3) notis = self.wd.page_source if ('感谢' in notis) or ('已经填报' in notis): message = '{}打卡成功'.format( str( time.strftime('%Y-%m-%d %H : %M: %S', time.localtime(time.time() + 8 * 3600)))) print(message) Wechat('打卡成功', message) return True return False
def test_video_album_create_edit_delete(self): success = True wd = self.wd wd.get(str(Baseurl.baseurl)) wd.find_element_by_link_text("Войти").click() wd.find_element_by_id("UserForm_email").click() wd.find_element_by_id("UserForm_email").clear() wd.find_element_by_id("UserForm_email").send_keys("*****@*****.**") wd.find_element_by_id("UserForm_password").click() wd.find_element_by_id("UserForm_password").clear() wd.find_element_by_id("UserForm_password").send_keys("1111") wd.find_element_by_id("submit_link").click() wd.find_element_by_xpath("//ul[@id='yw1']//strong[.=' Видео']").click() wd.find_element_by_xpath("//div[@class='btn__holder']//span[.='Добавить альбом']").click() wd.find_element_by_id("VideoAlbum_name").click() wd.find_element_by_id("VideoAlbum_name").clear() wd.find_element_by_id("VideoAlbum_name").send_keys("New album") wd.find_element_by_id("VideoAlbum_desc").click() wd.find_element_by_id("VideoAlbum_desc").clear() wd.find_element_by_id("VideoAlbum_desc").send_keys("Sample description") wd.find_element_by_css_selector("button.btn.btn_green").click() wd.find_element_by_xpath("//div[@class='company-box__section']//a[.='edit']").click() wd.find_element_by_id("VideoAlbum_name").click() wd.find_element_by_id("VideoAlbum_name").clear() wd.find_element_by_id("VideoAlbum_name").send_keys("New New album") wd.find_element_by_id("VideoAlbum_desc").click() wd.find_element_by_id("VideoAlbum_desc").clear() wd.find_element_by_id("VideoAlbum_desc").send_keys("Новое описание") wd.find_element_by_css_selector("button.btn.btn_green").click() wd.find_element_by_xpath("//div[@class='company-box__section']//a[.='edit']").click() if wd.find_element_by_id("VideoAlbum_desc").text != "Новое описание": success = False print("verifyText failed") wd.find_element_by_css_selector("div.form__del > label").click() wd.find_element_by_css_selector("button.btn.btn_green").click() wait(wd, 30).until(lambda s: "Ни одно видео еще не было загружено." in wd.find_element_by_xpath("//div[@class='company-box__section']//p").text) self.assertTrue(success)
def test_save_then_publish_vacancy(app): wd = app.wd actions = ActionChains(wd) app.open_page("resume") wd.find_element_by_xpath("//span[.='Разместить вакансию']").click() app.login(username="******", password="******") wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//input[@id='Vacancy_name']")) wd.find_element_by_xpath("//input[@id='Vacancy_name']").send_keys("Тест создания вакансии") wd.find_element_by_xpath("//span[@class='select2-chosen' and .='Проф. область']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Кино']").click() wd.find_element_by_xpath("//span[@class='select2-chosen' and .='Специальность']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Агент']").click() wd.find_element_by_xpath("//span[@class='select2-chosen' and .='Город']").click() wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Амстердам']").click() wd.find_element_by_xpath("//textarea[@id='Vacancy_smartDescription']").send_keys("Тест создания вакансии") wd.find_element_by_xpath("//input[@id='Vacancy_email']").send_keys("*****@*****.**") wd.find_element_by_xpath("//input[@id='Vacancy_company_name']").send_keys("Sample Company") button = wd.find_element_by_xpath("//input[@class='btn btn_green btn_green_big']") actions.move_to_element(button).perform() wd.find_element_by_xpath("//input[@name='save']").click() time.sleep(5) # даем возможность отправиться данным на сервер, без этого ожидания фэйлится app.open_page("job") # проверяем, что вакансия НЕ опубликована assert "Тест создания вакансии" != wd.find_element_by_xpath("//div[@class='items']/div[1]//a").text app.open_page("profile") # публикуем wd.find_element_by_xpath("//div[@class='user-inf__vacancy line']//a[.='Опубликовать']").click() time.sleep(5) app.open_page("job") # проверяем, что вакансия успешно опубликована assert "Тест создания вакансии" == wd.find_element_by_xpath("//div[@class='items']/div[1]//a").text app.open_page("profile") # восстанавливаем начальное состояние wd.find_element_by_xpath("//div[@class='user-inf__vacancy line']//a[.='Удалить']").click() time.sleep(5)
def test_buy_some_duck(chrome_driver): test_page = LiteCart(chrome_driver) test_page.go_to_site() for i in range(1, 4): test_page.get_first_duck().click() try: select_size = Select( chrome_driver.find_element_by_name("options[Size]")) select_size.select_by_value("Large") except NoSuchElementException: pass chrome_driver.find_element_by_name("add_cart_product").click() wait(chrome_driver, 10).until( EC.text_to_be_present_in_element((By.CLASS_NAME, "quantity"), str(i))) test_page.go_to_site() chrome_driver.find_element_by_link_text("Checkout »").click() remove_buttons = chrome_driver.find_elements_by_name("remove_cart_item") find_not_empty_rows_xpath = "*//div[@id='order_confirmation-wrapper']/table/tbody/tr" empty_cart_xpath = "*//div[@id='checkout-cart-wrapper']/p/em[text()='There are no items in your cart.']" for i in range(len(remove_buttons)): order_table_rows = chrome_driver.find_elements_by_xpath( find_not_empty_rows_xpath) # если утка не последняя - жждем появление иконки для остановки карусели и кликаем if i != len(remove_buttons) - 1: time.sleep(1) #wait(chrome_driver, 5).until(EC.presence_of_element_located((By.CLASS_NAME, "shortcuts"))) chrome_driver.find_element_by_class_name("shortcuts").click() wait(chrome_driver, 5).until(EC.element_to_be_clickable( (By.NAME, "remove_cart_item"))).click() time.sleep(1) if i == len(remove_buttons) - 1 and len( chrome_driver.find_elements_by_xpath(empty_cart_xpath)) == 1: pass else: wait(chrome_driver, 10).until(lambda chrome_driver: len( chrome_driver.find_elements(By.XPATH, find_not_empty_rows_xpath )) == len(order_table_rows) - 1)
def test_pavillion_price_request(app): wd = app.wd app.open_page("pavilions/97") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Запросить стоимость']")).click() app.login(username="******", password="******") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Запросить стоимость']")).click() # пока не удалось, но нужно устанавливать будущие даты # first_date = datetime.date.today() + datetime.timedelta(days=2) # дата начала срока аренды # last_date = datetime.date.today() + datetime.timedelta(days=5) # дата конца срока аренды current_date = strftime("%d.%m.%Y", gmtime()) wait(wd, 10).until(lambda s: wd.find_element_by_id("PavilionRequest_date_from")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_id("PavilionRequest_date_to")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='ui-dialog-buttonset']/button[1]")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='ui-dialog-buttonset']/button[1]")).click() # добавить проверку текста уведомления в админке
def wait_notEle_time(self, css, timeout): try: wait(self.__driver, timeout).until_not( lambda x: x.find_element_by_css_selector(css).is_displayed()) except: raise Exception("%s元素在%ss内未隐藏,页面加载超时!" % (css, timeout))
def save(self): wd = self.app.wd wd.find_element_by_xpath("//input[@name='save']").click() wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("div.vacancy"))
def test_articles_navigation(app, locator, url): wd = app.wd app.open_page("article") wd.find_element_by_xpath(str(locator)).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1")) assert wd.current_url == app.base_url + url
def main(): driver.get('https://web.whatsapp.com') wait(driver, 1000).until(EC.presence_of_element_located((By.ID, 'side'))) numbers = open("numbers.txt", "r") # number_list = numbers.readlines() number_list = range(79252393125, 79252394000) numbers.close() sended_count = 0 not_sended_count = 0 error_numbers_count = 0 for number in number_list: number = str(number) if number[-1] == '\n': number = number[:-1] if number[0] == '+' and number[1] == '7' and len(number) == 12: number = number[1:] if number[0] == '8' and len(number) == 11: number = '7' + number[1:] if number[0] != '7' or len(number) != 11: with open("error_numbers.txt", "a") as file: file.write(number + "\n") error_numbers_count += 1 continue if send(number): with open("sended.txt", "a") as file: file.write(number + "\n") sended_count += 1 else: with open("not_whatsapp.txt", "a") as file: file.write(number + "\n") not_sended_count += 1 print( f"Current: {number}, Sended: {sended_count}, Not WhatsApp: {not_sended_count}, All: {sended_count + not_sended_count + error_numbers_count}" ) driver.quit() with open("sended.txt", "r") as file: sended = file.read() with open("sended.txt", "w") as file: file.write(f"Отправлено на {sended_count} номеров\n\n\n") file.write(sended) with open("not_whatsapp.txt", "r") as file: not_whatsapp = file.read() with open("not_whatsapp.txt", "w") as file: file.write(f"Нет whatsapp у {not_sended_count} номеров\n\n\n") file.write(not_whatsapp) with open("error_numbers.txt", "r") as file: error_numbers = file.read() with open("error_numbers.txt", "w") as file: file.write(f"Ошибка отправки на {error_numbers_count} номеров\n\n\n") file.write(error_numbers)
def click_on_LogOut_link(self): element=wait(self.driver,10).until( ec.presence_of_element_located((By.LINK_TEXT, self.logOut_link))) element.click()
def click_on_Welcome_btn(self): element = wait(self.driver, 10).until( ec.presence_of_element_located((By.XPATH, self.welcome_link))) element.click()
def wait_results(self): wd = self.app.wd wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("div#companiesList div.items div.line, div#companiesList div.items div.empty"))
def wait_for_all_elements_presence(self, tuple_selector, timeout=constants.TIMEOUT): return wait(self.driver, timeout).until(EC.presence_of_all_elements_located(tuple_selector))
def wait_for_element_invisiable(self, tuple_selector, timeout=constants.TIMEOUT): return wait(self.driver, timeout).until(EC.invisibility_of_element_located(tuple_selector))
def respond_to(self, vacancy): wd = self.app.wd self.open_from_list(vacancy) wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("a.create-vacancy-response")).click() wait(wd, 10).until(ec.visibility_of_element_located((By.CSS_SELECTOR, "div.vacancy-response-popup span.btn__inner"))).click() wait(wd, 10).until(ec.visibility_of_element_located((By.CSS_SELECTOR, "div.response-sent")))
def open_from_list(self, vacancy): wd = self.app.wd self.app.open_page("job") wd.find_element_by_xpath("//a[.='%s']" % vacancy.title).click() wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("div.vacancy"))
def login(self, username, password): # метод заполняет поля и кликает сабмит на УЖЕ открытой странице авторизации wd = self.wd wait(wd, 10).until(lambda s: wd.find_element_by_id('UserForm_email')) wd.find_element_by_id('UserForm_email').send_keys(username) wd.find_element_by_id('UserForm_password').send_keys(password) wd.find_element_by_id('submit_link').click()
def getAboutTabSource(self): try: self.driver.get(self.aboutTab) if wait(self.driver, 10).until( EC.presence_of_element_located( (By.CSS_SELECTOR, '#container > yt-formatted-string'))): if re.compile('계정이 해지되었습니다.').search( self.driver.find_element_by_css_selector( '#container > yt-formatted-string').text): #if self.driver.find_element_by_css_selector('#container > yt-formatted-string').text == "스팸, 현혹 행위, 혼동을 야기하는 콘텐츠 또는 기타 서비스 약관 위반 등으로 YouTube의 정책을 여러 번 또는 심각하게 위반하여 계정이 해지되었습니다.": raise myError("채널이 삭제되었습니다.") wait(self.driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'body'))) self.scrollDown() self.aboutTab_src = self.driver.page_source self.aboutTab_parser = BeautifulSoup(self.aboutTab_src, 'html.parser') # 채널 제목 가져오기 self.channel_title = self.aboutTab_parser.select_one( '#channel-title').text # 구독자 수 가져오기 subs_cnt_parser = self.aboutTab_parser.select_one( '#subscriber-count').text[4:-1] if subs_cnt_parser.find(',') != -1: subs_cnt_parser = int(subs_cnt_parser.replace(',', '')) if subs_cnt_parser == '': self.subscriber_num = 0 else: self.subscriber_num = int(subs_cnt_parser) # 정보탭 섹션 정보 가져오기 elements_left = self.aboutTab_parser.select('#left-column > div') for element_left in elements_left: about_section_name = element_left.select_one( '.subheadline').text # 설명 정보 가져오기 if about_section_name == '설명': self.desc_size = len( element_left.select_one('#description').text) self.desc = element_left.select_one('#description').text # 장소 정보 가져오기 elif about_section_name == '세부정보': locVlaue_selector = 'table > tbody > tr:nth-of-type(2) > td:nth-of-type(2) > yt-formatted-string' if element_left.select_one(locVlaue_selector).text != '': self.location = element_left.select_one( locVlaue_selector).text else: self.location = 'NA' # 링크 정보 가져오기 elif about_section_name == '링크': links = element_left.select('#link-list-container > a') self.link_cnt = len(links) cnt = 0 for link in links: if re.compile('instagram', re.I).search(link['href']): self.instagram = True cnt += 1 elif re.compile('facebook', re.I).search(link['href']): self.facebook = True cnt += 1 elif re.compile('twitter', re.I).search(link['href']): self.twitter = True cnt += 1 elif re.compile('plus.google', re.I).search(link['href']): self.googleplus = True cnt += 1 elif re.compile('cafe.naver', re.I).search(link['href']): self.naver_cafe = True cnt += 1 elif re.compile('blog.naver', re.I).search(link['href']): self.naver_blog = True cnt += 1 elif re.compile('tistory', re.I).search(link['href']): self.tistory = True cnt += 1 elif re.compile('afreeca', re.I).search(link['href']): self.afreeca = True cnt += 1 elif re.compile('youtube', re.I).search(link['href']): self.youtube = True cnt += 1 elif re.compile('tumblur', re.I).search(link['href']): self.tumblur = True cnt += 1 if self.link_cnt - cnt != 0: self.others = True # 정보탭 통계 섹션 정보 가져오기 self.join_date = self.aboutTab_parser.select_one( '#right-column > yt-formatted-string:nth-of-type(2)' ).text.split(': ')[1] if self.aboutTab_parser.select_one( '#right-column > yt-formatted-string:nth-of-type(3)' ).text != '': total_view_cnt_selector = self.aboutTab_parser.select_one( '#right-column > yt-formatted-string:nth-of-type(3)' ).text.split(' ')[1][:-1] if total_view_cnt_selector.find(',') != -1: self.total_view_cnt = int( total_view_cnt_selector.replace(',', '')) else: self.total_view_cnt = int(total_view_cnt_selector) except myError as m: print(pcolors.EXPT + str(m) + pcolors.END) raise except Exception as e: print(pcolors.EXPT + self.channel_title + ', getAboutTabSource(), ' + str(e) + pcolors.END)
def test_user_can_post(app): wd = app.wd app.session.login_as(app.users["user1"]) # --------- сообщение с видео ----------- # если поставить последним в соответствии с номером вкладки - падает с Element Not Visible Exception app.open_page("comments/post/index/#tab03") video_text = "Posting video " + strftime("%H:%M:%S", gmtime()) wd.find_element_by_id("Post_video_link").send_keys("https://youtu.be/WvhmUzvhpx8") wd.find_element_by_xpath("//div[@id='tab03']//*[@id='Post_video_name']").send_keys("Sample video name") time.sleep(2) wd.find_element_by_xpath("//div[@id='tab03']//*[@id='Post_body']").send_keys(video_text) wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@id='tab03']//div[@class='form__bottom']/button")).click() time.sleep(3) assert video_text in wd.find_element_by_tag_name("body").text # --------- Текстовое сообщение ----------- app.open_page("comments/post/index") editor = wait(wd, 30).until(lambda s: wd.find_element_by_css_selector("iframe.cke_wysiwyg_frame")) wd.switch_to_frame(editor) post_text = "Sample post" + strftime("%H:%M:%S", gmtime()) wait(wd, 30).until(lambda s: wd.find_element_by_css_selector("body")).send_keys(post_text) wd.switch_to_default_content() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='form__bottom']/button")).click() time.sleep(3) assert post_text in wd.find_element_by_tag_name("body").text # проверили, что сообщение видно на стене в профиле # --------- Сообщение с фото ----------- app.open_page("comments/post/index/#tab02") image_file = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../images/company_logo.jpg")) wd.find_element_by_id("Post_image").send_keys(image_file) photo_text = "Photo comment" + strftime("%H:%M:%S", gmtime()) wd.find_element_by_xpath("//div[@id='tab02']//*[@id='Post_body']").send_keys(photo_text) wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@id='tab02']//div[@class='form__bottom']/button")).click() time.sleep(3) assert photo_text in wd.find_element_by_tag_name("body").text # ----------Проверки на странице /community ----------------------- app.open_page("community") assert post_text in wd.find_element_by_tag_name("body").text assert photo_text in wd.find_element_by_tag_name("body").text assert video_text in wd.find_element_by_tag_name("body").text # ---------- Зачистка ---------------------------------------------- app.open_page("comments/post/index") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//ul[@class='comments messages']/li[1]//a[@class='delete']")).click() time.sleep(2) alert = wd.switch_to_alert() alert.accept() time.sleep(5) # иначе удаляет не то, что нужно wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//ul[@class='comments messages']/li[1]//a[@class='delete']")).click() time.sleep(2) # иначе не видит алерт alert = wd.switch_to_alert() alert.accept() time.sleep(5) wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//ul[@class='comments messages']/li[1]//a[@class='delete']")).click() time.sleep(2) alert = wd.switch_to_alert() alert.accept() time.sleep(5)
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait as wait driver = webdriver.Chrome() driver.get("http://www.amazon.in") elem = driver.find_element_by_name("field-keywords") elem.clear() elem.send_keys("mobiles") elem.send_keys(Keys.RETURN) wait(driver, 10) result_list = driver.find_element_by_id("s-results-list-atf") print(result_list.text)
def test_company_create(app): wd = app.wd app.open_page("login") app.login(username="******", password="******") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Добавить компанию']")) wd.find_element_by_xpath("//span[.='Добавить компанию']").click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//input[@id='Company_title']")) wd.find_element_by_xpath("//input[@id='Company_title']").send_keys("Sample company") wd.find_element_by_xpath("//li//span[.='Оборудование']").click() #попытка переключиться во фрейм wysiwyg и ввести текст editor = wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("iframe.cke_wysiwyg_frame")) wd.switch_to_frame(editor) wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("body")).send_keys("Sample description") wd.switch_to_default_content() image_file = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../images/company_logo.jpg")) wd.find_element_by_name("image").send_keys(image_file) wait(wd, 10).until(lambda s: wd.find_element_by_id("button_crop_recortar")).click() crop_button = wait(wd, 10).until(ec.element_to_be_clickable((By.ID, "button_crop_original"))) time.sleep(2) crop_button.click() wait(wd, 10).until(ec.staleness_of(crop_button)) pass
def logout(driver): driver.find_element_by_id('welcome').click() wait(driver, 2).until( expected_conditions.visibility_of_element_located( (By.LINK_TEXT, 'Logout'))).click()
def send(number): driver.get('https://web.whatsapp.com/send?phone=' + number) driver.execute_script("window.onbeforeunload = function() {};") wait(driver, 1000).until(EC.presence_of_element_located((By.ID, 'side'))) try: wait(driver, 2).until( EC.presence_of_element_located( (By.XPATH, not_number_in_whatsapp_xpath))) return False except TimeoutException: pass input_box = wait(driver, 1000).until( EC.presence_of_element_located((By.XPATH, input_box_xpath))) input_box.send_keys(message) input_box.send_keys(Keys.ENTER) wait(driver, 1000).until_not( EC.presence_of_element_located( (By.CSS_SELECTOR, sending_clock_icon_selector))) attach_button = wait(driver, 1000).until( EC.presence_of_element_located((By.XPATH, attach_button_xpath))) attach_button.click() input_image = wait(driver, 1000).until( EC.presence_of_element_located((By.XPATH, input_image_xpath))) input_image.send_keys(file_path) image_text_input = wait(driver, 1000).until( EC.presence_of_element_located((By.XPATH, image_text_input_xpath))) image_text_input.send_keys(message_for_image) image_text_input.send_keys(Keys.ENTER) wait(driver, 1000).until( EC.presence_of_element_located( (By.CSS_SELECTOR, sending_clock_icon_selector))) wait(driver, 1000).until_not( EC.presence_of_element_located( (By.CSS_SELECTOR, sending_clock_icon_selector))) return True
targetSize = "XL" driverPath = r"/Users/Unchained_Erbo/Downloads/chromedriver" chrome_options = webdriver.ChromeOptions() prefs = {"profile.managed_dfault_content_settings.images": 2} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(driverPath, options=chrome_options) driver.get(addr) # In[169]: size = driver.find_element_by_id("SIZE") Select(size).select_by_visible_text(targetSize) wait(driver, 3).until(EC.element_to_be_clickable((By.NAME, "add"))) purchase = driver.find_element_by_name("add") time.sleep(0.3) purchase.click() # In[170]: checkout = driver.find_element_by_name("checkout") checkout.click() # In[156]:
def test_user_can_create_event(app): wd = app.wd app.session.login_as(app.users["user2"]) app.open_page("events") wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[.='Создать событие']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//span[@class='select2-chosen']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//div[@class='select2-result-label' and .='Кастинг']")).click() event_name = "Тест создания" + strftime("%H:%M:%S", gmtime()) # делаем имя уникальным для возможности повторного запуска wd.find_element_by_id("Event_title").send_keys(event_name) image_file = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../images/event_logo.jpg")) wd.find_element_by_name("image").send_keys(image_file) wait(wd, 60).until(lambda s: wd.find_element_by_id("button_crop_recortar")).click() crop_button = wait(wd, 60).until(ec.element_to_be_clickable((By.ID, "button_crop_original"))) time.sleep(5) crop_button.click() wait(wd, 60).until(ec.staleness_of(crop_button)) current_date = strftime("%m/%d/%Y", gmtime()) #переделать на генерацию будущих дат wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_start_date")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_end_date")).send_keys(current_date) wait(wd, 10).until(lambda s: wd.find_element_by_id("town_id")).send_keys("Москва") wait(wd, 10).until(lambda s: wd.find_element_by_id("Event_address")).send_keys("Адрес события, 123") editor = wait(wd, 60).until(lambda s: wd.find_element_by_css_selector("iframe.cke_wysiwyg_frame")) wd.switch_to_frame(editor) wait(wd, 60).until(lambda s: wd.find_element_by_css_selector("body")).send_keys("Sample description") wd.switch_to_default_content() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//input[@class='btn btn_green']")).click() wait(wd, 10).until(lambda s: wd.find_element_by_xpath("//h1")) assert wd.find_element_by_xpath("//h1").text == event_name #можно добавить удаление в админке
def wait_for_element_clickable(self, tuple_selector, timeout=constants.TIMEOUT): return wait(self.driver, timeout).until(EC.element_to_be_clickable(tuple_selector))
def test_AP_single_article_view(app): wd = app.wd app.session.login_as(app.users["admin"]) app.open_page("admin/article/index") wd.find_element_by_xpath("//a[@class='view']").click() wait(wd, 60).until(lambda s: len(wd.find_elements_by_xpath("//table[@class='articledispl']")) > 0)
while notFind: try: div = driver.find_element_by_xpath( "//*[@id='yeezy-boost-350-v2-static-3m-reflective-soon']/div/div[3]" ) size = div.find_element_by_xpath(".//*[@id='SIZE']") size.send_keys(Keys.NULL) for i in range(5): ic.search_friends(nickName="Erbo_Unchained")[0].send("Yeezy is up") time.sleep(0.1) break except NoSuchElementException: time.sleep(15) driver.refresh() Select(size).select_by_visible_text("S/M") wait(driver, 5).until(EC.element_to_be_clickable((By.NAME, "add"))) purchase = driver.find_element_by_name("add") time.sleep(0.3) purchase.click() time.sleep(0.7) wait(driver, 3).until(EC.element_to_be_clickable((By.NAME, "checkout"))) checkout = driver.find_element_by_name("checkout") checkout.click() driver.find_element_by_name("checkout[email]").send_keys(shipping1[0]) driver.find_element_by_name( "checkout[shipping_address][first_name]").send_keys(shipping1[1]) driver.find_element_by_name("checkout[shipping_address][last_name]").send_keys( shipping1[2]) driver.find_element_by_name("checkout[shipping_address][address1]").send_keys( shipping1[3])
def login(self): try: mobile = {"deviceName": "iPhone X"} option = webdriver.ChromeOptions() option.add_experimental_option('mobileEmulation', mobile) option.add_argument('--disable-infobars') option.add_argument("--disable-extensions") option.add_argument("--disable-gpu") option.add_argument("--disable-dev-shm-usage") option.add_argument("--no-sandbox") option.add_argument("--headless") #如果配置环境变量可以不写绝对路径 wd = webdriver.Chrome(chrome_options=option) wd.set_window_size(600, 800) wd.get("http://jksb.zzu.edu.cn/") wd.switch_to.frame(0) try: wait(wd, 30, poll_frequency=0.5).until( ec.presence_of_element_located( (By.NAME, 'uid'))).send_keys(self.uid) time.sleep(0.5) wait(wd, 10, poll_frequency=0.5).until( ec.visibility_of_element_located( (By.NAME, "upw"))).send_keys(self.pwd) time.sleep(0.5) wait(wd, 10, poll_frequency=0.5).until( ec.element_to_be_clickable( (By.XPATH, ".//div[@class='mt_3e']/input"))).submit() time.sleep(0.5) # wd.switch_to.frame('zzj_top_6s') # time.sleep(0.5) except TimeoutException: raise TimeoutError #切入frame wd.switch_to.frame('zzj_top_6s') time.sleep(0.5) init = wait(wd, 60, poll_frequency=0.5).until( ec.presence_of_element_located( (By.XPATH, '//*[@id="bak_0"]/div[7]/span'))) init_text = init.text if '已经填报' in init_text: # if '1' in init_text: #self.fp.writelines(u"{} --> 打卡成功 -->已填报过了 无需重复填写 ^_^ \n ".format(time.strftime("%Y-%m-%d %H : %M: %S", time.localtime()))) print(u"{} 已完成上报啦 ,无需重复啦 ^_^ ".format( time.strftime("%Y-%m-%d %H : %M: %S", time.localtime(time.time() + 8 * 3600)))) time.sleep(5) sys.exit() else: wait(wd, 10, poll_frequency=1).until( ec.element_to_be_clickable( (By.XPATH, '//*[@id="bak_0"]/div[13]/div[5]/div[4]'))).click() # Select(wd.find_element_by_xpath('//*[@id="bak_0"]/div[8]/select')).select_by_value("正常") # wait(wd, 10, poll_frequency=0.5).until(ec.element_to_be_clickable((By.XPATH, '//*[@id="bak_0"]/div[13]/div[4]/span'))).click() wait(wd, 10, poll_frequency=0.5).until( ec.element_to_be_clickable( (By.XPATH, '//*[@id="bak_0"]/div[11]/div[4]/span'))).click() # notis = wd.find_element_by_xpath('//*[@id="bak_0"]/div[2]/div[2]/div[2]/div[2]').text notis = wd.page_source # init = wait(wd , 60 ,poll_frequency=0.5).until(ec.presence_of_element_located((By.XPATH , '//*[@id="bak_0"]/div[7]/span'))) # pattern = re.compile(r"感谢您向学校上报健康状况") # pattern = re.compile(r"感谢你今日上报健康状况!") # confirm = re.findall(pattern, notis)# if ('感谢' in notis) or ('已经填报' in notis): today = "{} --> 打卡成功 --> ^_^\n".format( str( time.strftime( u"%Y-%m-%d %H : %M: %S", time.localtime(time.time() + 8 * 3600)))) print(today) Wechat("打卡成功", today) #self.fp.writelines(today) time.sleep(3) else: raise TimeoutError # wd.quit() except (TimeoutError, SessionNotCreatedException): while 1: if self.i <= 3: error = u"{} --> 打卡失败 --> 已进行第{}次重试 (┬_┬) \n".format( str( time.strftime( u"%Y-%m-%d %H : %M: %S", time.localtime(time.time() + 8 * 3600))), str(self.i)) #self.fp.writelines(error) print(error) self.i += 1 try: # wd.close() wd.quit() except: pass time.sleep(4) self.login() else: error2 = u"{} --> 打卡失败 --> 已尝试{}次且未成功 , 打卡失败请重试!! (┬_┬) \n".format( str( time.strftime( u"%Y-%m-%d %H : %M: %S", time.localtime(time.time() + 8 * 3600))), str(self.i)) #self.fp.writelines(error2) print(error2) Wechat("打卡失败", error2) break finally: try: wd.quit() except: pass
def welcome_message_method(driver): condition = wait(driver, 2).until( EC.presence_of_element_located((By.ID, 'welcome'))) return condition.text
def init_vacancy_creation(self): wd = self.app.wd self.app.open_page("resume") wd.find_element_by_xpath("//span[.='Разместить вакансию']").click() wait(wd, 60).until(lambda s: wd.find_element_by_xpath("//input[@id='Vacancy_name']"))
def wait_results(self): wd = self.app.wd wait(wd, 10).until(lambda s: wd.find_element_by_css_selector("h1.cnt__ttl").text == "Результаты поиска")