Python selenium.common.exceptions 模块,StaleElementReferenceException() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.common.exceptions.StaleElementReferenceException()。
def get_row(self, column_name, text, exact_match=True):
"""Get row that contains specified text in specified column.
In case exact_match is set to True,text contained in row must equal
searched text,otherwise occurrence of searched text in the column
text will result in row match.
"""
def get_text(element):
text = element.get_attribute('data-selenium')
return text or element.text
for row in self.rows:
try:
cell = row.cells[column_name]
if exact_match and text == get_text(cell):
return row
if not exact_match and text in get_text(cell):
return row
# NOTE(tsufiev): if a row was deleted during iteration
except exceptions.StaleElementReferenceException:
pass
return None
def expand_tree(self, node_count):
"""expand_tree expands treeview (dynatree) by clicking expander arrows one by one"""
self.wait_for_frameworks()
webdriverwait(self.selenium, 10).until(EC.element_to_be_clickable(self.expander_locator))
webdriverwait(self.selenium, 10).until(lambda _: len(self.expanders) == node_count)
# least-work way to fight ElementNotVisibleException: Message: Cannot click on element,and
# http://stackoverflow.com/questions/37781539/selenium-stale-element-reference-element-is-not-attached-to-the-page-document/38683022
def loop():
self.wait_for_frameworks()
for expander in self.expanders: # type: WebElement
node = self.retry_on_exception(NoSuchElementException, lambda: expander.find_element(By.XPATH, './..'))
if self.is_expanded(node):
continue
self.wait_for_frameworks()
expander.click()
self.wait_for_frameworks()
self.retry_on_exception(StaleElementReferenceException, loop)
self.assert_tree_expanded()
def _click_action(self, locator, timeout=10.0):
driver = self.driver
try:
element = webdriverwait(driver, float(timeout)).until(EC.element_to_be_clickable(locator),
self._get_trace())
except StaleElementReferenceException:
driver.implicitly_wait(2)
element = webdriverwait(driver,
self._get_trace())
except WebDriverException:
driver.implicitly_wait(1)
element = webdriverwait(driver,
self._get_trace())
try:
element.click()
except WebDriverException:
sleep(1)
element = webdriverwait(driver,
self._get_trace())
element.click()
def select_state_option(self, value, dowait=True):
'''
Select state value from dropdown. Wait until district dropdown
has loaded before returning.
'''
#path = '//select[@id="variation-tablepress-32"]'
path = '//select[@id="variation-tablepress-31"]'
district_select_elem = self.driver.find_element_by_xpath(path)
def district_select_updated(driver):
try:
district_select_elem.text
except StaleElementReferenceException:
return True
except:
pass
return False
state_select = self.get_state_select()
state_select.select_by_value(value)
return self.get_state_select()
def get_body_text(driver,
exponential_multiplier=cfg_wait_exponential_multiplier,
exponential_max=cfg_wait_exponential_max,
stop_max_attempt=cfg_retry_stop_max_attempt):
@retry(
wait_exponential_multiplier=exponential_multiplier,
wait_exponential_max=exponential_max,
stop_max_attempt_number=stop_max_attempt)
def _get_body_text(driver):
try:
e = wait_for_xpath_presence(driver, "//body")
except StaleElementReferenceException:
a_nice_refresh(driver)
e = wait_for_xpath_presence(driver, "//*")
raise StaleElementReferenceException
return e.get_attribute("outerHTML")
return _get_body_text(driver)
# Subbornly clicks on the elements which run away from the DOM
def click_stubborn(driver, e, xpath):
logging.debug("Starting stubborn clicks")
MAX_ATTEMPT = 6
attempt = 0
while attempt < MAX_ATTEMPT:
try:
for i in range(10):
attempt += 1
e.click()
break
# breaks if no exception happens
break
except StaleElementReferenceException:
a_nice_refresh(driver)
e = wait_for_xpath_presence(driver, xpath)
except WebDriverException:
break
return e
def attemptInput(by, key, maxAttempts):
#def attemptInput(value,idKey,maxAttempts):
result = False
attempts = 0
while (attempts < maxAttempts):
try:
driver.find_element(by, key).send_keys(value)
result = True
break
except StaleElementReferenceException:
attempts = attempts + 1
return result
def attemptInput(by, key).send_keys(value)
result = True
break
except StaleElementReferenceException:
attempts = attempts + 1
return result
def get_row(self, columns, exact_match=True):
"""Get row that contains specified text in specified column.
In case exact_match is set to True,otherwise occurrence of searched text in the column
text will result in row match.
"""
def get_text(element):
text = element.get_attribute('data-selenium')
return text or element.text
for row in self.rows:
try:
match_flag = True
for column_name, column_value in columns.items():
if not match_flag:
break
cell = row.cells[column_name]
if exact_match:
if column_value != get_text(cell):
match_flag = False
else:
if column_value in get_text(cell):
match_flag = False
if match_flag:
return row
# NOTE(tsufiev): if a row was deleted during iteration
except exceptions.StaleElementReferenceException:
pass
return None
def _is_element_displayed(self, element):
if element is None:
return False
try:
if isinstance(element, webelement.WebElement):
return element.is_displayed()
else:
return element.src_elem.is_displayed()
except (Exceptions.ElementNotVisibleException,
Exceptions.StaleElementReferenceException):
return False
def _execute(self, command, params=None):
"""Overriding in order to catch StaleElementReferenceException."""
# (schipiga): not need to use while True,trying to catch StaleElement
# exception,because driver.implicitly_wait delegates this to browser.
# Just we need to catch StaleElement exception,reload chain of element
# parents and then to execute command again.
repeat = range(2)
for i in repeat:
try:
return super(WebElementWrapper, self)._execute(command, params)
except exceptions.StaleElementReferenceException:
if i == repeat[-1]:
raise
if not self._reload_element():
raise
def __call__(self, driver):
try:
actual = _find_element(driver, self.locator).text
if not type(actual) is str:
actual = actual.encode('unicode-escape')
actual = self.setCase(actual)
#print "Comparing '{0}' and '{1}'".format(actual,self.expected)
return actual == self.expected
except StaleElementReferenceException:
return False
def __call__(self, driver):
try:
return _element_if_visible(_find_element(driver, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, driver):
try :
element_text = _find_element(driver, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self, driver):
try:
element_text = _find_element(driver,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self, self.locator), False)
except (NoSuchElementException, StaleElementReferenceException):
# In the case of NoSuchElement,returns true because the element is
# not present in DOM. The try block checks if the element is present
# but is invisible.
# In the case of StaleElementReference,returns true because stale
# element reference implies that element is no longer visible.
return True
def __call__(self, driver):
try:
element = _find_element(driver, self.locator)
return element.is_selected() == self.is_selected
except StaleElementReferenceException:
return False
def __call__(self, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self, driver):
try:
return not _find_element(driver, self.locator).is_displayed()
except (NoSuchElementException,returns true because stale
# element reference implies that element is no longer visible.
return True
def assert_tree_expanded(self):
def loop():
self.wait_for_frameworks()
assert all(self.is_expanded(e.find_element(By.XPATH, './..')) for e in self.expanders)
self.retry_on_exception(StaleElementReferenceException, loop)
def __call__(self, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, driver):
try:
elements = _find_elements(driver, self.locator)
for element in elements:
if _element_if_visible(element, visibility=False):
return False
return elements
except StaleElementReferenceException:
return False
def __call__(self, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self,returns true because stale
# element reference implies that element is no longer visible.
return True
def __call__(self, self.locator)
return element.is_selected() == self.is_selected
except StaleElementReferenceException:
return False
def waitText(self, css: str,timeOut: float=60, pollFreq: float=3.0) -> str:
begin = time.time()
while (time.time()-begin) < timeOut:
try:
return self.waitVisible(css, pollFreq).text
except (TimeoutException, StaleElementReferenceException):
time.sleep(pollFreq)
timeElapsed += (time.time()-beginTime)
continue
except Exception as ex:
print(ex)
return None
return None
def getElemText(self: WebElement, timeOut: float=60.0, pollFreq=3.0) -> str:
while (time.time()-begin) < timeOut:
try:
return self.text.strip()
except StaleElementReferenceException:
time.sleep(pollFreq)
raise TimeoutException("[getElemText] elem=%s"%WebElement)
def login(driver):
'''
Logs into the BSEStar web portal using login credentials defined in settings
'''
try:
line = "https://www.bsestarmf.in/Index.aspx"
driver.get(line)
print("Opened login page")
# enter credentials
userid = webdriverwait(driver, 10).until(EC.presence_of_element_located((By.ID, "txtUserId")))
memberid = webdriverwait(driver, "txtMemberId")))
password = webdriverwait(driver, "txtPassword")))
userid.send_keys(settings.USERID[settings.LIVE])
memberid.send_keys(settings.MEMBERID[settings.LIVE])
password.send_keys(settings.PASSWORD[settings.LIVE])
submit = driver.find_element_by_id("btnLogin")
submit.click()
print("Logged in")
return driver
except (TimeoutException, NoSuchElementException, StaleElementReferenceException,
ErrorInResponseException, ElementNotVisibleException):
print("retrying in login")
return login(driver)
except (BadStatusLine):
print("retrying for BadStatusLine in login")
driver = init_driver()
return login(driver)
def update_transaction_status(self, driver):
'''
Updates status of all transactions that need a status update (i.e. not completed or Failed)
incl SIP transactions which have instalment order due today
'''
try:
# order_id (identifier of each transaction on BSEStar) is necessary to check status on web portal
# its returned by create_transaction_bse() api call but
# SIP investments constitute of several instalments each of which has an order_id
# so,save order_id of all sip instalment orders that are due today
dt = date.today()
find_sip_order_id(driver, dt)
# update status of all orders incl sip instalment orders
update_order_status(driver)
return driver
except (TimeoutException, ErrorInResponseException, ElementNotVisibleException):
print("retrying")
return update_transaction_status(driver)
except (BadStatusLine):
print("retrying for BadStatusLine in login")
driver = init_driver()
driver = login(driver)
return update_transaction_status(driver)
def __call__(self, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self,returns true because stale
# element reference implies that element is no longer visible.
return True
def attemptInput(by, key).send_keys(value)
result = True
break
except StaleElementReferenceException:
attempts = attempts + 1
return result
def element_has_gone_stale(element):
'''Checks if element has gone stale
Args:
element (selenium.webdriver.remote.webelement.WebElement): Selenium webelement to check for.
Returns:
bool: True if element has gone stale,False otherwise.
Examples:
::
from selenium_extensions.helpers import element_has_gone_stale
if element_has_gone_stale(your_element):
pass # Do something
::
from selenium_extensions.helpers import wait_for_function_truth
from selenium_extensions.helpers import element_has_gone_stale
login_btn = driver.find_element_by_class_name('login_btn')
wait_for_function_truth(element_has_gone_stale,element)
'''
try:
# Poll the object with an arbitrary call
element.find_elements_by_id('non-existing-id')
return False
except StaleElementReferenceException:
return True
def __call__(self, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self,returns true because stale
# element reference implies that element is no longer visible.
return True
def __call__(self, self.locator))
except StaleElementReferenceException:
return False
def __call__(self, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False
def __call__(self,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False
def __call__(self,returns true because stale
# element reference implies that element is no longer visible.
return True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。