def wait_updates(): self.wait.until_not(EC.text_to_be_present_in_element_value( (By.CLASS_NAME, 'js-cart-size'), '' )) self.wait.until_not(EC.text_to_be_present_in_element_value( (By.CLASS_NAME, 'js-mobile-cart-price'), '' ))
def testExpectedConditionTextToBePresentInElementValue(self, driver, pages): pages.load('booleanAttributes.html') with pytest.raises(TimeoutException): WebDriverWait(driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) driver.execute_script("setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)") WebDriverWait(driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) assert 'Example Expected text' == driver.find_element_by_id('inputRequired').get_attribute('value')
def businessinsider_fetch_links(string,driver): check_sum=0 links_fetched = [] try: driver.get('http://www.businessinsider.com/?IR=C') check_sum=1 WebDriverWait(driver, 100).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[4]/div[1]/div/div[3]/div/ul[2]/div/li[3]/a[1]/i'))) except: while check_sum==1: try: driver.get('http://www.businessinsider.com/?IR=C') WebDriverWait(driver, 100).until(EC.element_to_be_clickable((By.XPATH,'/html/body/div[4]/div[1]/div/div[3]/div/ul[2]/div/li[3]/a[1]/i'))) check_sum=0 except: print "Network Error... Trying to Reconnect!!!" time.sleep(5) try: driver.find_element_by_xpath('/html/body/div[4]/div[1]/div/div[3]/div/ul[2]/div/li[3]/a[1]/i').click() except: time.sleep(2) driver.find_element_by_xpath('/html/body/div[4]/div[1]/div/div[3]/div/ul[2]/div/li[3]/a[1]/i').click() try: driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/form/input').send_keys('"'+string+'"',Keys.RETURN) except: driver.find_element_by_xpath('/html/body/div[4]/div[1]/div/div[3]/div/ul[2]/div/li[3]/a[1]/i').click() time.sleep(2) driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/form/input').send_keys('"'+string+'"',Keys.RETURN) try: WebDriverWait(driver,1000).until(EC.text_to_be_present_in_element_value((By.XPATH,'//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3'))) driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3') except: time.sleep(10) if driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3').text.split()[-2].strip()=='no': driver.quit() return [] elif driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3').text.split()[-2].strip().isalpha: page=0 else: page=int(driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3').text.split()[-2].strip())/20 while page>=0: elem=driver.find_elements_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/div/div[2]/h3/a') date=driver.find_elements_by_class_name('river-post__date') for i,j in zip(elem,date): i=i.get_attribute('href') j=int(j.text.split(',')[1].strip()) if j<=2008 and i not in links_fetched: links_fetched.append(i) if page>0: try: driver.find_element_by_xpath('//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/ul/li[2]/a').click() WebDriverWait(driver,100).until(EC.text_to_be_present_in_element_value((By.XPATH,'//*[@id="main-content"]/div[2]/div/div/div/div[2]/div/div[2]/div[1]/h3'))) except: '''Do Nothing...''' page-=1 driver.quit() return links_fetched
def testExpectedConditionTextToBePresentInElementValue(self): self._loadPage('booleanAttributes') try: WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) self.fail("Expected TimeoutException to have been thrown") except TimeoutException as e: pass self.driver.execute_script("setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)") WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) self.assertEqual('Example Expected text', self.driver.find_element_by_id('inputRequired').get_attribute('value'))
def get_stock_price(self, symbol): symbol_input_xpath = "/html/body/form/table[3]/tbody/tr/td[1]/table/tbody/tr/td/table[2]/tbody/tr/td/table[1]/tbody/tr[1]/td[2]/input" refresh_xpath = "/html/body/form/table[3]/tbody/tr/td[1]/table/tbody/tr/td/table[2]/tbody/tr/td/table[1]/tbody/tr[1]/td[2]/span/a" price_xpath = "/html/body/form/table[3]/tbody/tr/td[1]/table/tbody/tr/td/table[2]/tbody/tr/td/table[1]/tbody/tr[4]/td[2]" self.enter_stock_menu() time.sleep(3) self.select_menu_frame() element = self.driver.find_element_by_xpath("/html/body/table[2]/tbody/tr[1]/td/a") element.click() time.sleep(3) self.select_main_frame() element = self.driver.find_element_by_xpath(symbol_input_xpath) element.send_keys(symbol) time.sleep(3) element = self.driver.find_element_by_xpath(refresh_xpath) element.click() time.sleep(3) # wait the price is not 0 WebDriverWait(self.driver, 10).until_not( EC.text_to_be_present_in_element_value((By.XPATH, price_xpath), "0") ) element = self.driver.find_element_by_xpath(price_xpath) if element.text == "0": self.logger.critical("Price is 0") price = float(element.text) return price
def wait_for_first_host_active(self, value): xpath_loc = ( AmazonEc2Locators.Ec2Locators.STATUS_LABEL_PREFIX + "1" + AmazonEc2Locators.Ec2Locators.STATUS_LABEL_SUFFIX ) print xpath_loc element = self.driver.find_element(xpath_loc) element = WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element_value(element, value))
def testExpectedConditionTextToBePresentInElementValue(self): self._loadPage('booleanAttributes') try: WebDriverWait(self.driver, 1).until(EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def assert_element_text_value(self, how, what, text, message): try: return WebDriverWait(self.driver, 10).until( EC.text_to_be_present_in_element_value((how, what), text) ) except: self.fail(message)
def go_to_next_page(driver,current_page): next_button = driver.find_elements_by_id("MainContent_GridView1_ButtonNext") if(len(next_button) == 0): return 1 while True: try: next_button[0].click() WebDriverWait(driver,100).until( EC.text_to_be_present_in_element_value( (By.ID,"MainContent_GridView1_PageCurrent"),`current_page+1` ) ) break except: print("Took too long to go to the next page, going to click again") return 0
def is_text_present_in_element(locator, text, timeOut=0): ''' Checking if the given text is present in the specified element\n ''' try: _wait(timeOut).until(EC.text_to_be_present_in_element_value(Element(locator)._get(), text)) except WebDriverException: return False return True
def test_submit_invalid_number(url): """ Example test using Selenium to submit an HTML form. Assumption is that the result will display an error if invalid input is submitted. """ driver = None try: driver = webdriver.Firefox() wait = WebDriverWait(driver, 10) driver.get(url) input_field = driver.find_element_by_id('number') button = driver.find_element_by_id('getFibNumber') invalid_number = 'Hello world!' input_field.send_keys(invalid_number) button.click() try: wait.until(ec.text_to_be_present_in_element_value( (By.ID,'number'),'Invalid number')) except TimeoutException: # Expected response not found, continue with assert traceback.print_exc() result = input_field.get_attribute('value') assert result != invalid_number, 'No error message was displayed for invalid input' except OSError as e: #Firefox not installed, skip test print "Skipping Selenium test, Firefox not installed/found" finally: if driver: driver.quit()
def test_submit_valid_number(url): """ Example test using Selenium to submit an HTML form. This assumes Firefox is installed. Asserts will be skipped if Firefox cannot be found. """ driver = None try: driver = webdriver.Firefox() wait = WebDriverWait(driver, 10) driver.get(url) input_field = driver.find_element_by_id('number') button = driver.find_element_by_id('getFibNumber') input_field.send_keys('4') button.click() try: wait.until(ec.text_to_be_present_in_element_value((By.ID,'number'),'3')) except TimeoutException: # Expected response not found, continue with assert traceback.print_exc() assert input_field.get_attribute('value') == '3' except OSError as e: #Firefox not installed, skip test print "Skipping Selenium test, Firefox not installed/found" finally: if driver: driver.quit()
async def solve_captcha(url, api, driver, timestamp): driver.get(url) WebDriverWait(driver, 86400).until(EC.text_to_be_present_in_element_value((By.NAME, "g-recaptcha-response"), "")) driver.switch_to.frame(driver.find_element_by_xpath("//*/iframe[@title='recaptcha challenge']")) token = driver.find_element_by_id("recaptcha-token").get_attribute("value") request = api.create_request() request.verify_challenge(token=token) request.get_hatched_eggs() request.get_inventory(last_timestamp_ms=timestamp) request.check_awarded_badges() request.get_buddy_walked() request.check_challenge() for attempt in range(-1, conf.MAX_RETRIES): try: response = await request.call() return response['responses']['VERIFY_CHALLENGE']['success'] except (ex.HashServerException, ex.MalformedResponseException, ex.ServerBusyOrOfflineException) as e: if attempt == conf.MAX_RETRIES - 1: raise else: print('{}, trying again soon.'.format(e)) await sleep(4) except ex.NianticThrottlingException: if attempt == conf.MAX_RETRIES - 1: raise else: print('Throttled, trying again in 11 seconds.') await sleep(11) except (KeyError, TypeError): return False
def check_if_text_present_in_element_value(webdriver, locator, text, message='text not present in element value', timeout=2): try: WebDriverWait(webdriver, timeout).until( expected_conditions.text_to_be_present_in_element_value(locator, text), message) return True except TimeoutException: return False
def wait_for_value(self, css_selector, text, timeout=10): """ Helper function that blocks until the value is found in the css selector. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until(ec.text_to_be_present_in_element_value((By.CSS_SELECTOR, css_selector), text), timeout)
def wait_for_value(self, css_selector, text, timeout=10): """ Block until the value is found in the CSS selector. """ from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec self.wait_until( ec.text_to_be_present_in_element_value( (By.CSS_SELECTOR, css_selector), text), timeout)
def is_text_present_in_element_value(self, locator, expected_text, timeout=5): try: return WebDriverWait(self.driver, timeout).until( EC.text_to_be_present_in_element_value(locator, expected_text)) except TimeoutException: return False
def is_value_in_element(self, locator, value=''): """返回bool值,value为空字符串,返回False""" if not isinstance(locator, tuple): raise LocatorTypeError("参数类型错误,locator必须是元祖类型:loc = ('id','value1')") try: result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value)) return result except: return False
def step_impl(context, text_string, element_name): element_id = 'customer_' + element_name.lower().replace(" ", "_") # element = context.driver.find_element_by_id(element_id) # expect(element.get_attribute('value')).to_equal(text_string) time.sleep(5) found = WebDriverWait(context.driver, WAIT_SECONDS).until( expected_conditions.text_to_be_present_in_element_value( (By.ID, element_id), text_string)) expect(found).to_be(True)
def step_impl(context): button = context.browser.find_element_by_xpath('//*[@id="form_78ea690540a24bd8b9dcfbf99e999fea"]/div[1]/div[5]/input') button.click() try: WebDriverWait(context.browser, 10).until(EC.text_to_be_present_in_element_value((By.ID, 'msg_78ea690540a24bd8b9dcfbf99e999fea'), 'Thank you sending us your information. We will get back to you with your Chai :)')) except(Exception): traceback.print_exc() # context.browser.find_element_by_xpath('//*[@id="form_78ea690540a24bd8b9dcfbf99e999fea"]/div[1]/div[1]/input and @class="form-value form-value-invalid"')
def is_value_in_element(self, locator, _value=''): '''返回bool值, value为空字符串,返回Fasle''' if not isinstance(locator, tuple): print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")') try: result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, _value)) return result except: return False
def fill_in_id(id, text, browser): WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.ID, id))) field = browser.find_element_by_id(id) field.clear() field.send_keys(text) WebDriverWait(browser, 5).until( EC.text_to_be_present_in_element_value((By.ID, id), text)) return "filled"
def check_value_in_element(self,locator,text,timeout=10): try: result = WebDriverWait(self.driver,timeout).until\ (EC.text_to_be_present_in_element_value(locator,text)) except: print(f'元素没有找到 -> {locator}') return False else: return result
def get_element_value(self,locator,text,timeout=10): """判断一个元素的value值与输入的text是否相等""" try: result = WebDriverWait(self.driver, timeout).until(EC.text_to_be_present_in_element_value(locator,text)) except: print(f"{locator}元素未找到") return False else: return result
def fill_field_and_check_value_click_on_focus(self, locator, text, focus_locator, locator_type='css'): self.click_on_elem(locator) self.find_element_by_locator(locator).send_keys(text) self.wait_until_located(focus_locator, 'css', 6) # todo тип фокус локатора self.click_on_elem(focus_locator) if locator_type == 'css': WebDriverWait(self.browser, 4).until( EC.text_to_be_present_in_element_value( (By.CSS_SELECTOR, locator), text), 'text not found in css') else: WebDriverWait(self.browser, 4).until( EC.text_to_be_present_in_element_value( (By.XPATH, locator), text), 'text not found in xpath')
def step_impl(context, text_string, element_name): if element_name.upper() == 'ID': element_id = 'input' + element_name.upper() else: element_id = 'input' + element_name.title() found = WebDriverWait(context.driver, WAIT_SECONDS).until( expected_conditions.text_to_be_present_in_element_value( (By.ID, element_id), text_string)) expect(found).to_be(True)
def testExpectedConditionTextToBePresentInElementValue(self): self._loadPage('booleanAttributes') try: WebDriverWait(self.driver, 1).until( EC.text_to_be_present_in_element_value( (By.ID, 'inputRequired'), 'Expected')) self.fail("Expected TimeoutException to have been thrown") except TimeoutException, e: pass
def set_chosen_single(driver, id, value): """Gets the chosen single-select element of the passed id and attempts to select the passed value. :param driver: The driver used to find the html element :param id: The id of the chosen single-select :param value: The text value to select from the chosen select :raises: ValueError: Could not find the value in the chosen single-select :raises: TimeoutException: Could not find an element of the passed id :returns: None """ id += "_chosen" # find the chosen single-select and its parent and wait until they are clickable chosen = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.ID, id))) parent = WebDriverWait(chosen, 3).until( EC.element_to_be_clickable((By.XPATH, '../..'))) # click parent to remove inconsistencies involving parent divs containing multiple elements parent.click() chosen.click() # sleep to allow time for ?something? time.sleep(.1) # find the textbox inside the single-select and wait until it is clickable text = WebDriverWait(chosen, 3).until( EC.presence_of_element_located( (By.XPATH, './/input[@type="text"][@autocomplete="off"]'))) # enter value into the textbox and wait until the value is present text.send_keys(value) WebDriverWait(chosen, 3).until( EC.text_to_be_present_in_element_value( (By.XPATH, './/input[@type="text"][@autocomplete="off"]'), value)) # get the results from entering the value into the textbox results = WebDriverWait(chosen, 3).until( EC.presence_of_all_elements_located( (By.CSS_SELECTOR, ".chosen-results li"))) # check to see if there is an exact match in results and click it values = [] for result in results: values.append(result.text) if result.text == value: result.click() WebDriverWait(driver, 3).until( EC.text_to_be_present_in_element( (By.XPATH, './/div[@id="' + id + '"]/a[@class="chosen-single"]/span'), value)) return raise ValueError("Could not find value: '" + str(value) + "' for chosen-single-select: '" + id + "'. Values availible: " + ', '.join(values))
def is_text_in_value(self, locator, value): """判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值""" try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, value)) except TimeoutException: self.log.error('元素没有定位到:%s' % str(locator)) return False else: return result
def is_value_in_element(self, locator, _value): if not isinstance(locator, tuple): print("locator参数类型错误,必须传元组类型:loc= ('id', 'value1')") '''返回bool值, value为空字符串,返回False''' try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, _value)) return result except: return False
def step_impl(context, text_string, element_name): element_name = element_name.replace(" ", "_") element_id = element_name.lower() found = WebDriverWait(context.driver, WAIT_SECONDS).until( expected_conditions.text_to_be_present_in_element_value( (By.ID, element_id), text_string ) ) expect(found).to_be(True)
def is_value_in_element(self, locator, _value, timeout=4, t=0.5): try: result = WebDriverWait(self.driver, timeout, t).until( EC.text_to_be_present_in_element_value(locator, _value)) print(result) return result except: return False
def wait_for_text_to_be_present_in_element_value(self, locator, text, timeout=None): timeout = constants.ELEMENT_WAIT_TIMEOUT if timeout is None else timeout _log.debug( "wait for text to be present in element value: locator=%s, text='%s', timeout=%s", locator, text, timeout) return self.wait(timeout).until( EC.text_to_be_present_in_element_value(locator, text))
def text_to_be_in_element_value(self, locator, text): #判断文本是否在元素的值中 try: ele = WebDriverWait(self.driver, self.timeout, self.poll_frequency).until( Ec.text_to_be_present_in_element_value( locator, text)) return ele except: return False
def is_text_in_value(self, locator, value): """判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值""" try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, value)) except TimeoutException: log.error("元素的value值没有定位到:{}".format(locator)) raise NoSuchElementException("{} 元素的value值没有定位到".format(locator)) else: return result
def assert_text_in_element_value(self, locator, value, timeout=10): ''' 判断定位元素的value值是否为预期结果 :param locator: 元素定位 :param value: value的值 :param timeout: 超时时间 :return: 返回True或者False ''' WebDriverWait(self.driver, timeout, 1).until( EC.text_to_be_present_in_element_value(locator, value))
def is_value_in_element(self, locator, value=""): if not isinstance(locator, tuple): raise LocatorTypeError( self.log.info("参数类型错误,locator必须是元祖类型:loc = ('id','value1')")) try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, value)) return result except: return False
def testExpectedConditionTextToBePresentInElementValue(self): self._loadPage('booleanAttributes') try: WebDriverWait(self.driver, 1).until( EC.text_to_be_present_in_element_value( (By.ID, 'inputRequired'), 'Expected')) self.fail("Expected TimeoutException to have been thrown") except TimeoutException as e: pass self.driver.execute_script( "setTimeout(function(){document.getElementById('inputRequired').value = 'Example Expected text'}, 200)" ) WebDriverWait(self.driver, 1).until( EC.text_to_be_present_in_element_value((By.ID, 'inputRequired'), 'Expected')) self.assertEqual( 'Example Expected text', self.driver.find_element_by_id('inputRequired').get_attribute( 'value'))
def is_value_in_element(self, locator, _value=''): if not isinstance(locator, tuple): print('locator参数类型错误,必须穿元祖类') try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, _value)) return result except: return False
def text_to_be_present_in_element_Value(self, locator, value): """判断元素的value与预期结果是否一致,返回bool值,元素定位出错了不会报错,只会返回False""" if not isinstance(locator, tuple): print("locator必须传元祖类型") try: result = WebDriverWait(self.driver, self.timeout, self.t).until( EC.text_to_be_present_in_element_value(locator, value)) return result except: return False
def is_value_in_element(self, key, value, value1): self.logging.info("校验元素value值是否为:{}".format(value1)) if WebDriverWait(self.driver, self.timeout).until( EC.text_to_be_present_in_element_value( self.get_element(key, value), value1)): self.logging.info("校验通过!") else: self._get_windows_img() self.logging.info("校验失败!") raise StaleElementReferenceException
def tsi_create(): # probably not necessary element = wait( 10, EC.presence_of_element_located((By.ID, 'InsertButton'))) # wait for KA to populate serial number before filling dropdowns element = wait( 30, EC.text_to_be_present_in_element_value( (By.ID, 'elogic_serialnumber'), serial))
def is_value_in_element(self, locator, value=""): """判断value是不是包含在元素里面,返回bool值""" if not isinstance(locator, tuple): raise LocatorTypeError("参数类型错误,locator必须是元组类型,loc = ('id','value1')") else: try: result = WebDriverWait(self.driver, self.timeout, self.times).until(EC.text_to_be_present_in_element_value(locator,value)) return result except: return False
def _order_ticket(self): # 1. 跳转到查票的界面 self.driver.get(self.search_url) # 2. 等待出发地是否输入正确 WebDriverWait(self.driver, 1000).until( EC.text_to_be_present_in_element_value((By.ID, 'fromStationText'), self.from_station) ) # 3. 等待目的地是否输入正确 WebDriverWait(self.driver, 1000).until( EC.text_to_be_present_in_element_value((By.ID, 'toStationText'), self.to_station) ) # 4. 等待出发日是否输入正确 WebDriverWait(self.driver, 1000).until( EC.text_to_be_present_in_element_value((By.ID, 'train_date'), self.depart_time) ) # 5. 等待查询按钮是否可以点击 WebDriverWait(self.driver, 1000).until( EC.element_to_be_clickable((By.ID, 'query_ticket')) ) # 6. 如果能被点击,执行点击事件 searchBtn = self.driver.find_element_by_id('query_ticket') searchBtn.click() # 7. 点击查询按钮以后,等待车次信息是否显示出来了 WebDriverWait(self.driver, 1000).until( EC.presence_of_element_located((By.XPATH, './/tbody[@id="queryLeftTable"]/tr')) ) # 8. 出现车次信息后,找到想要的车次信息 tr_list = self.driver.find_elements_by_xpath('.//tbody[@id="queryLeftTable"]/tr[not(@datatran)]') # 9. 遍历所有车次列表 for tr in tr_list: train_number = tr.find_element_by_class_name('number').text if train_number in self.trains: left_ticket = tr.find_element_by_xpath(".//td[4]").text if left_ticket == '有' or left_ticket.isdigit: print(train_number + "有票") orderBtn = tr.find_element_by_class_name('btn72') orderBtn.click() # 等待是否跳转到确认乘客的页面 WebDriverWait(self.driver, 1000).until( EC.url_to_be(self.passenger_url) )
def test_tc1(self): driver = self.driver driver.get(self.base_url + "/") driver.find_element_by_name("first_name").clear() driver.find_element_by_name("first_name").send_keys("Goerge") driver.find_element_by_name("last_name").clear() driver.find_element_by_name("last_name").send_keys("Peng") driver.find_element_by_css_selector("input[type=\"submit\"]").click() element = WebDriverWait(driver, 10).until( expected_conditions.text_to_be_present_in_element_value((By.CSS_SELECTOR, 'body'), 'First name') )
def password_error(self): """ 判断是否密码错误 :return: """ try: return WebDriverWait(self.browser, 5).until( EC.text_to_be_present_in_element_value( (By.CLASS_NAME, 'error'), '你输入的密码和账户名不匹配')) except TimeoutException: return False
def is_value_in_element(self, locator, value, timeout=global_timeout): '''元素中的value断言''' try: result = WebDriverWait(self.driver, timeout, 1).until( EC.text_to_be_present_in_element_value(locator, value)) except TimeoutException as msg: log.error(u"超时:[%s]" % msg) return False else: return result
def wait_for_form_item_to_contain(self, item=None, text=None): item = HitchSeleniumItem(item) if item.is_id: WebDriverWait(self.driver, self.wait_for_timeout).until( EC.text_to_be_present_in_element_value((By.ID, item.html_id), text) ) else: full_xpath = """//*[{}][{}]""".format( " and ".join([ """contains(concat(' ', normalize-space(@class), ' '), ' {} ')""".format( class_name ) for class_name in item.html_classes] ), str(item.index + 1) if item.index >= 0 else "last()" ) WebDriverWait(self.driver, self.wait_for_timeout).until( EC.text_to_be_present_in_element_value( (By.XPATH, full_xpath), text ) )
def is_text_in_value(self, locator, value, timeout=10): ''' 判断元素的value值,没定位到元素返回false,定位到返回判断结果布尔值 result = driver.text_in_element(locator, text) ''' try: result = WebDriverWait(self.driver, timeout, 1).until(EC.text_to_be_present_in_element_value(locator, value)) except TimeoutException: print "元素没定位到:"+str(locator) return False else: return result
def waitPlaytime(wait_time): try: playtime = browser.find_element_by_id("playTimeShow") play_time = playtime.get_attribute("value") print(play_time) time.sleep(1) element = WebDriverWait(browser, wait_time).until_not( EC.text_to_be_present_in_element_value((By.ID, "playTimeShow"), play_time) ) if element: print("Test passed") except Exception as e: print(e) print("Test may be failed, please check if you are still online or not")
def create_ptt(self, name=None): """Create a personaltimetable with the provided name when provided""" self.find(( By.XPATH, "//button[contains(@class,'add-button')]//i[contains(@class,'fa fa-plus')]" )).click() name_input = self.find((By.CLASS_NAME, 'timetable-name')) WebDriverWait(self.driver, self.TIMEOUT) \ .until(EC.text_to_be_present_in_element_value( (By.CLASS_NAME, 'timetable-name'), 'Untitled Schedule' )) if name: name_input.clear() name_input.send_keys(name)
def test_copy_to_existing_semester_displays_error_message(self): """ Trying to copy a course into a semester that already exists should display an error message """ self.admin_log_in_complete() self.check_admin_class_modal() test_class = self.browser.find_element_by_xpath('//div[@id="add_semester"]/ul[@class="dropdown-menu"]/li[@class="text-left select-semester"][1]/a') test_class.click() text_wait = WebDriverWait(self.browser, 3).until( EC.text_to_be_present_in_element_value((By.ID,'class_name'), 'test class')) self.assertTrue(self.check_exists_by_id('class_name')) self.assertTrue(self.check_exists_by_id('obj_bank_id')) self.assertTrue(self.check_exists_by_id('semester')) self.assertTrue(self.check_exists_by_id('new_semester')) class_name = self.browser.find_element_by_id('class_name') obj_bank_id = self.browser.find_element_by_id('obj_bank_id') semester = self.browser.find_element_by_id('semester') new_semester = self.browser.find_element_by_id('new_semester') self.assertEqual( class_name.get_attribute('value'), 'test class') self.assertEqual( obj_bank_id.get_attribute('value'), self.obj_bank_id.replace('\n','')) # Hack! self.assertEqual( semester.get_attribute('value'), 'Spring 2012') new_semester.send_keys('Spring 2012') ok_modal_btn = self.browser.find_element_by_link_text('OK') ok_modal_btn.click() modal_status_box = self.browser.find_element_by_id('status_box') self.assertEqual( modal_status_box.text, 'Your new semester cannot already exist')
def fill_form(self, form_data): """ Fill in the form with the given data. """ for field, value in form_data.items(): element = self.form.find_element_by_name(field) if element.get_attribute('type') == 'checkbox': if bool(value) != element.is_selected(): element.click() # Before moving on, make sure checkbox state (checked/unchecked) corresponds to desired value WebDriverWait(self.client, timeout=5) \ .until(expected_conditions.element_selection_state_to_be(element, value)) elif not element.get_attribute('readonly') and not element.get_attribute('type') == 'hidden': element.clear() element.send_keys(value) # Before moving on, make sure input field contains desired text WebDriverWait(self.client, timeout=5) \ .until(expected_conditions.text_to_be_present_in_element_value((By.NAME, field), value))
def wait_for_value(self, selector='', value='', **kwargs): ''' Wait for an element to contain a specific string. Parameters ---------- selector: str A CSS selector to search for. This can be any valid CSS selector. value: str The string to look for. This must be precise. (Case, punctuation, UTF characters... etc.) kwargs: Passed on to _wait_for ''' self._wait_for(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR, selector), value), **kwargs)
def send_keys_and_wait(self, keys: str, locator, expected_keys=''): """ Safely send keys to element with given locator. :param keys: should consist of letters, digits and spaces. No special symbols """ # `keys` should not contain special symbols. # For example backspace characters don't appear in input field. assert re.match(r'[\w\d\s\-_]+', keys, re.I | re.U), \ 'Form text should not contain special symbols' el = self.wait.until(EC.visibility_of_element_located(locator)) el.clear() str_keys = str(keys) el.send_keys(str_keys) self.wait.until( EC.text_to_be_present_in_element_value( locator, expected_keys or str_keys ) )
def test_1(self): self.driver.get(self.host + "/lp_tester.s.html") snippets = self.driver.find_elements_by_class_name("code_snippet") self.assertEqual(len(snippets), 2) check_button = self.driver.find_element_by_id('e1') result_area = self.driver.find_element_by_id('lp-result') # Set snippets. self.driver.execute_script('LPList["e1"].textAreas[0].setValue("xxx"); LPList["e1"].textAreas[1].setValue("yyy");') self.assertFalse(result_area.text) # Click the test button. check_button.click() WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element_value((By.ID, 'lp-result'), 'Building...')) # Refresh the page. See if saved snippets are restored. self.driver.get(self.host + "/lp_tester.s.html") # Wait for script to run. I don't see a wait condition what would work, unfortunately. sleep(0.5) self.assertEqual(self.driver.execute_script('return LPList["e1"].textAreas[0].getValue();'), 'xxx') self.assertEqual(self.driver.execute_script('return LPList["e1"].textAreas[1].getValue();'), 'yyy')
def get_token(self, url): token = '' path = os.getcwd() if _platform == "Windows" or _platform == "win32": # Check if we are on 32 or 64 bit file_name= 'chromedriver.exe' if _platform.lower() == "darwin": file_name= 'chromedriver' if _platform.lower() == "linux" or _platform.lower() == "linux2": file_name = 'chromedriver' full_path = '' if os.path.isfile(path + '/' + file_name): # check local dir first full_path = path + '/' + file_name if full_path == '': self.bot.logger.error(file_name + ' is needed for manual captcha solving! Please place it in the bots root directory') sys.exit(1) try: driver = webdriver.Chrome(full_path) driver.set_window_size(600, 600) except Exception: self.bot.logger.error('Error with Chromedriver, please ensure it is the latest version.') sys.exit(1) driver.get(url) elem = driver.find_element_by_class_name("g-recaptcha") driver.execute_script("arguments[0].scrollIntoView(true);", elem) self.bot.logger.info('You have 1 min to solve the Captcha') try: WebDriverWait(driver, 60).until(EC.text_to_be_present_in_element_value((By.NAME, "g-recaptcha-response"), "")) token = driver.execute_script("return grecaptcha.getResponse()") driver.close() except TimeoutException, err: self.bot.logger.error('Timed out while trying to solve captcha')
def select_tab_and_token(self, tabname, token): """ Select a tab and then select a token by serial """ self.select_tab(tabname) # Now wait for token field to be visible WebDriverWait(self.driver, 5).until( EC.visibility_of_element_located((By.CSS_SELECTOR, self.selected_token_css))) # Assume, that there is any token/button in the token list # on the left side. WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.XPATH, '//*[@id="tokenDiv"]/ul/li/button'))) # Here we get ALL buttons on the page. Doesn't matter, since there # shouldn't be one, whoms text starts with the token serial; # Except the token button we search. buttons = self.driver.find_elements(By.XPATH, '//button') for button in buttons: # == 0 means here, starts with. if button.text.find(token) == 0: button.click() break # Wait for token field value to update try: WebDriverWait(self.driver, 5).until( EC.text_to_be_present_in_element_value((By.CSS_SELECTOR, self.selected_token_css), token)) except TimeoutException: logger.error( 'selfservice was not able to activate tab:%s token:%s', tabname, token) raise
def test_ac_single_item_type(admin_client, live_server, webdriver): selenium = webdriver() selenium.implicitly_wait(3) try: create_correct_sample_data() selenium.get(live_server + '/new_item_and_order/') login_as_admin(selenium) serial_nr = selenium.find_element_by_id('id_serial_nr') suggs = selenium.find_elements_by_class_name( 'autocomplete-suggestions') assert len(suggs) == 1 sugg = selenium.find_elements_by_class_name('autocomplete-suggestion') assert len(sugg) == 0 serial_nr.send_keys('0') selenium.implicitly_wait(1) sugg = selenium.find_elements_by_class_name('autocomplete-suggestion') assert len(sugg) == 10 serial_nr.send_keys('000001\t') selenium.find_element_by_id('id_name').send_keys("") wait = WebDriverWait(selenium, 5) assert wait.until(EC.text_to_be_present_in_element_value( (By.ID, 'id_name'), 'Item 1')) finally: selenium.quit()
def wait_until_text_shown_up(driver, wait_time, list_identifier, text): return WebDriverWait(driver, wait_time).until(EC.text_to_be_present_in_element_value(list_identifier, text))