Python selenium.common.exceptions 模块,NoSuchElementException() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.common.exceptions.NoSuchElementException()。
def assert_exists(self, selector):
'''
Asserts that the element found from a given CSS selector exists on the page.
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
'''
exists = True
try:
self.get_element(selector)
except NoSuchElementException:
exists = False
msg = 'An element Could not be found for the selector: {}'.format(selector)
assert exists == True, msg
def _is_element_present(self, *locator):
with self.waits_disabled():
try:
self._get_element(*locator)
return True
except Exceptions.NoSuchElementException:
return False
def login():
"""??????,??????????"""
driver.get(start_url)
wait = webdriverwait(driver,10)
try:
username = wait.until(EC.presence_of_element_located((By.ID,"loginname")))
password = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input')))
username.send_keys(user)
password.send_keys(passwd)
btn = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[6]/a/span')))
btn.click()
except TimeoutException:
print ("??")
return
except NoSuchElementException:
print ("?????? ")
return
def test_click_text_missing(self):
self.get_url('list_things')
self.assertRaises(NoSuchElementException,
lambda: self.click(text='Edit Fridge', wait_timeout=0))
self.assertRaises(NoSuchElementException,
lambda: self.click(text='Edit Rock',
text_parent_id='fribble',
wait_timeout=0))
def is_element_present(self, css_selector):
"""
Returns True if the element specified by the CSS selector is present on the current page,
False otherwise.
"""
try:
self._driver.find_element_by_css_selector(css_selector)
except NoSuchElementException:
return False
return True
def is_element_present(cls, xpath):
try:
cls.browser.find_element_by_xpath(xpath)
except NoSuchElementException:
return False
return True
def go_to_overview(self, name):
_network_items_locator = (by.By.CSS_SELECTOR, 'a[href$="/detail"]')
net_items = self._get_elements(*_network_items_locator)
for item in net_items:
if item.text == name:
item.click()
break
else:
raise exceptions.NoSuchElementException(
"Not found element with text: %s" % name)
return NetworkOverviewPage(self.driver, self.conf, name)
def test_unavailable_users_list_for_unprivileged_user(self):
self.assertRaises(NoSuchElementException,
self.home_pg.go_to_identity_userspage)
users_url = self.home_pg.conf.dashboard.dashboard_url.rstrip('/') + \
'/identity/users/'
self.driver.get(users_url)
users_page = UsersPage(self.driver, self.home_pg.conf)
self.assertTrue(users_page.find_message_and_dismiss(messages.INFO))
self.assertFalse(users_page.visible_user_names)
def _is_element_visible(self, *locator):
try:
return self._get_element(*locator).is_displayed()
except (Exceptions.NoSuchElementException,
Exceptions.ElementNotVisibleException):
return False
def _get_element_id(self, *locator):
try:
return self.driver.find_element(*locator).id
except (Exceptions.NoSuchElementException,
Exceptions.ElementNotVisibleException):
return None
def __init__(self, driver, conf, level=SUCCESS):
self._default_src_locator = self._msg_locator(level)
# NOTE(tsufiev): we cannot use self._turn_off_implicit_wait() at this
# point,because the instance is not initialized by ancestor's __init__
driver.implicitly_wait(0)
try:
super(MessageRegion, self).__init__(driver, conf)
except NoSuchElementException:
self.src_elem = None
finally:
self._turn_on_implicit_wait()
def select_by_value(self, value):
"""Select all options that have a value matching the argument. That is,when given "foo" this
would select an option like:
<option value="foo">Bar</option>
:Args:
- value - The value to match against
throws NoSuchElementException If there is no option with specisied value in SELECT
"""
css = "option[value =%s]" % self._escapestring(value)
opts = self._el.find_elements(By.CSS_SELECTOR, css)
matched = False
for opt in opts:
self._setSelected(opt)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Cannot locate option with value: %s" % value)
def deselect_by_value(self, value):
"""deselect all options that have a value matching the argument. That is,when given "foo" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- value - The value to match against
throws NoSuchElementException If there is no option with specisied value in SELECT
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
matched = False
css = "option[value = %s]" % self._escapestring(value)
opts = self._el.find_elements(By.CSS_SELECTOR, css)
for opt in opts:
self._unsetSelected(opt)
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with value: %s" % value)
def deselect_by_index(self, index):
"""deselect the option at the given index. This is done by examing the "index" attribute of an
element,and not merely by counting.
:Args:
- index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specisied index in SELECT
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
for opt in self.options:
if opt.get_attribute("index") == str(index):
self._unsetSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index)
def login(self, email, password):
"""Log to facebook using email (str) and password (str)"""
url = "https://mbasic.facebook.com"
self.get(url)
email_element = self.find_element_by_name("email")
email_element.send_keys(email)
pass_element = self.find_element_by_name("pass")
pass_element.send_keys(password)
pass_element.send_keys(Keys.ENTER)
try:
self.find_element_by_name("xc_message")
print("Logged in")
return True
except NoSuchElementException as e:
print("Fail to login")
return False
def messagetoUrl(self, url, text):
"""Message a profile/fanpage (str) with text(str)"""
self.get(url)
name = self.title
try:
mb = self.find_elements_by_class_name("bx")
except NoSuchElementException:
print("Can't message to ", name)
return False
mm = None
for m in mb:
if "messages" in m.get_attribute('href'):
mm = m.get_attribute('href')
break
self.get(mm)
b = self.find_element_by_name("body")
b.send_keys(text)
self.find_element_by_name("Send").click()
return True
def _get_element(self, locator, **kwargs):
"""gets the element with matching criteria
uses other private methods """
findall = kwargs.get('findall', None)
prefix, value = self._parse_locator(locator)
if prefix is None:
raise ValueError(("Strategy to find elements is "\
"not provided in the locator={0}".format(locator)))
locator_function = self._get_strategy_function(prefix)
if not locator_function:
raise ValueError(("{0} in locator={1} is not a "\
"supported strategy to find elements.".format(prefix, locator)))
try:
element = locator_function(value, findall)
except NoSuchElementException as exception:
#print_exception(exception)
element = None
else:
print_debug("Element found")
return element
def _drag_and_drop_by_offset(self, source, **kwargs):
"""Holds down the left mouse button on the source element,
then moves to the target offset and releases the mouse button
:Arguments:
1. source = a valid WebElement
2. xoffset = X offset to move to
3. yoffset = Y offset to move to
"""
status = True
print_info("drag and drop an element with offset")
try:
xoffset = kwargs.get('xoffset')
yoffset = kwargs.get('yoffset')
browser_instance = kwargs.get('browser')
actions = ActionChains(browser_instance)
actions.drag_and_drop_by_offset(source, xoffset, yoffset).perform()
except NoSuchElementException as e:
print_error("NoSuchElementException occurred")
status = False
except Exception as e:
print_error("An Exception Occurred {}".format(e))
status = False
return status
def parse_icon_mats(mats):
mat_data = []
# this needs optimization,it takes quite a while to get all the data out of the mats
for mat in mats:
# dp(mat.get_attribute('innerHTML'))
mat_img = mat.find_element_by_tag_name('img').get_attribute('src')
try:
mat_qty = mat.find_element_by_css_selector('div.quantity_small.Nowrap').text
except NoSuchElementException:
mat_qty = "1"
mat_url = mat.find_element_by_tag_name('a').get_attribute('href')
mat_data.append({'img': mat_img, 'qty': mat_qty, 'url': mat_url})
return mat_data
#click on the Next button if it isn't disabled and kick off another parsing.
def check_reload(self, args):
self.proc = subprocess.Popen(args, cwd=CURDIR, env=ENV)
self.wait()
self.wd.get(self.url)
h1 = self.get_element_by_id('h1')
self.assertEqual(h1.text, 'FirsT')
with open(self.tmpfilename, 'w') as f:
f.write(src_base.replace('FirsT', 'SECOND'))
for i in range(50):
self.wait_short()
try:
h1 = self.wd.find_element_by_id('h1')
except NoSuchElementException:
continue
if h1.text == 'SECOND':
break
self.assertEqual(h1.text, 'SECOND')
self.proc.terminate()
self.proc.wait()
def check_css_reload(self, env=ENV)
self.wait()
self.wd.get(self.url)
h1 = self.get_element_by_id('h1')
# value_of_css_property return colors as rgba style
self.assertRegex(h1.value_of_css_property('color'),
r'0,\s*0,\s* 0,\s*1\s*')
with open(css_path, 'w') as f:
f.write(src_css_post)
for i in range(50):
self.wait_short()
try:
h1 = self.wd.find_element_by_id('h1')
except NoSuchElementException:
continue
if '255' in h1.value_of_css_property('color'):
break
self.assertRegex(h1.value_of_css_property('color'),
r'255,\s*1\s*')
self.proc.terminate()
self.proc.wait()
def __getattr__(self, attr: str) -> Connection:
"""Call methods related to this controller."""
global conn
def wrapper(*args: str) -> str:
conn.send({'target': self.target, 'method': attr, 'args': args})
res = wait_for()
if isinstance(res, str):
if res.startswith('Error NoSuchElement'):
raise NoSuchElementException(res)
elif res.startswith('Error'):
raise ValueError(res)
return res
if attr in self.properties:
return wrapper()
return wrapper
def test_replace_child(self):
child1 = Tag()
child1.textContent = 'child1'
child2 = Tag()
child2.textContent = 'child2'
self.root.appendChild(child1)
with self.assertRaises(NoSuchElementException):
self.set_element(child2, self.wait_time * 10)
self.set_element(child1)
self.wait_until(lambda: self.element.text == 'child1')
self.assertEqual(self.element.text, 'child1')
self.root.replaceChild(child2, child1)
with self.assertRaises(NoSuchElementException):
self.wait(0.1)
self.set_element(child1, self.wait_time * 10)
self.set_element(child2)
self.wait_until(lambda: self.element.text == 'child2')
self.assertEqual(self.element.text, 'child2')
def select_by_index(self, index):
"""Select the option at the given index. This is done by examing the "index" attribute of an
element,and not merely by counting.
:Args:
- index - The option at this index will be selected
"""
match = str(index)
matched = False
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with index %d" % index)
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 state(self):
"""
Check the current status of the alarm system.
"""
# Click the refresh button to verify the state if it was made somewhere else
try:
# Recheck the current status
self._driver.get(self._driver.current_url)
current_status = webdriverwait(self._driver, self.timeout).until(EC.presence_of_element_located((self.STATUS_IMG[0],
self.STATUS_IMG[1]))).text
_LOGGER.debug('Fetched current status from system: {}'.format(current_status))
return current_status
except (exceptions.NoSuchElementException, exceptions.NoSuchWindowException, exceptions.TimeoutException, urllib.error.URLError) as e:
_LOGGER.warning('Error while checking alarm status. Attempting login again.')
self._login()
current_status = webdriverwait(self._driver,
self.STATUS_IMG[1]))).text
return current_status
def action(self, decision=False):
"""
click elements on pop message Box
:arg
decision: False --> cancel button,True --> upgrade button
"""
if decision:
id = "android:id/button1"
else:
id = "android:id/button2"
try:
btn = self.get_upgrade_btn_by_id(id=id)
except NoSuchElementException:
btn = None
assert btn is not None
screen_shot(driver=self.driver, filename=self.CLASS_NAME + ".png")
if decision:
logger.info(self.CLASS_NAME + " click upgrade button.")
else:
logger.info(self.CLASS_NAME + " click cancel button.")
btn.click()
def run_all_methods(driver):
"""
run white list
return?
False ? represents find and deal with
True : don't deal with
"""
logger.info(" Run all kNown message Box to deal with the situation.")
white_list = []
upgrade_msg_Box = UpgradeMessageBox(driver)
white_list.append(upgrade_msg_Box)
for x in white_list:
logger.info(x.CLASS_NAME)
try:
res = x.action()
except NoSuchElementException:
raise NoSuchElementException()
if res and white_list.index(x) != len(white_list):
return False
return True
def execises_logout(self):
"""Exercises logout helper."""
wait = webdriverwait(self.driver, 3)
try:
wait.until(
expect.element_to_be_clickable(
(By.ID, 'navbar-dropdown')
)
).click()
wait.until(
expect.element_to_be_clickable(
(By.CSS_SELECTOR, '[type="submit"]')
)
).click()
self.page.wait_for_page_load()
except NoSuchElementException:
# Different page,but uses the same logic and link text
self.find(By.CSS_SELECTOR, '[data-method]').click()
def frame(self, frame_reference):
"""
Switches focus to the specified frame,by index,name,or webelement.
:Args:
- frame_reference: The name of the window to switch to,an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
driver.switch_to.frame('frame_name')
driver.switch_to.frame(1)
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
"""
if isinstance(frame_reference, basestring) and self._driver.w3c:
try:
frame_reference = self._driver.find_element(By.ID, frame_reference)
except NoSuchElementException:
try:
frame_reference = self._driver.find_element(By.NAME, frame_reference)
except NoSuchElementException:
raise NoSuchFrameException(frame_reference)
self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})
def select_by_value(self, css)
matched = False
for opt in opts:
self._setSelected(opt)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Cannot locate option with value: %s" % value)
def deselect_by_index(self,and not merely by counting.
:Args:
- index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specisied index in SELECT
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
for opt in self.options:
if opt.get_attribute("index") == str(index):
self._unsetSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index)
def lagou_filter(browser, job_list, company_name, job_filter):
'''filter by job types'''
while True:
lagou_page(browser, job_filter)
#check next page
try:
pages = browser.find_element_by_class_name('pages')
spans = pages.find_elements_by_tag_name('span')
span = get_next_span(spans)
if span:
span.click()
time.sleep(SLEEPTIME)
else:
return
except NoSuchElementException as _e:
print(_e)
return
def check_basic_ui(self):
# ?????????
try:
self.browser.find_element_by_id('control-panel')
except NoSuchElementException:
self.fail('Please add a control panel')
# ?????????
try:
self.browser.find_element_by_id('presentation-name')
except NoSuchElementException:
self.fail('Please add a presentation-name input')
# ?????demo?????
try:
self.browser.switch_to.frame('impress-frame')
self.browser.switch_to.parent_frame()
except NoSuchFrameException:
self.fail('Please add a impress-frame')
def enter_search_term(browser, search_term):
wait = webdriverwait(browser, 10)
try:
search_bar = wait.until(EC.presence_of_element_located(
(By.XPATH, "//input[@id='autocomplete-input']")))
button = wait.until(EC.element_to_be_clickable(
(By.XPATH, "//button[@class='button-primary-alternative']")))
search_bar.click()
time.sleep(randint(10, 15))
search_bar.clear()
time.sleep(randint(10, 15))
search_bar.send_keys(search_term)
time.sleep(randint(10, 15))
button.click()
print("search-button has been clicked")
time.sleep(randint(15, 20))
return True
except (TimeoutException, NoSuchElementException) as e:
print(str(e))
return False
# Scrape the resulting page and move on to the next page until hitting the predefined lastpage. All results are stored in a csv-file
def select_by_index(self,and not merely by counting.
:Args:
- index - The option at this index will be selected
"""
match = str(index)
matched = False
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with index %d" % index)
def scrape():
driver = webdriver.PhantomJS()
driver.get('http://quotes.toscrape.com/js-onclick')
while True:
sel = parsel.Selector(text=driver.page_source)
for quote in sel.css('div.quote'):
print({
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('span small::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
})
try:
next_button = driver.find_element_by_css_selector('li.next > a')
next_button.click()
except NoSuchElementException:
break
def show_all_articles(driver: webdriver):
try:
show_more_button = driver.find_element_by_css_selector(SHOW_MORE_BUTTON)
max_clicks = 10
counter = 0
# click up to 11 times - see bug ED-2561
while show_more_button.is_displayed() and counter <= max_clicks:
show_more_button.click()
counter += 1
if counter > max_clicks:
with assertion_msg(
"'Show more' button didn't disappear after clicking on it"
" for %d times", counter):
assert counter == max_clicks
take_screenshot(driver, NAME + " after showing all articles")
except NoSuchElementException:
logging.debug("nothing to click as 'Show More' button is not visible")
def do_check_modules(self):
logger.info('Checking ClipBucket modules')
self.get('/admin_area/cb_mod_check.PHP')
for module_element in self._driver.find_elements_by_class_name('well'):
ui.webdriverwait(
self._driver, TIMEOUT).until(
expected_conditions.visibility_of(module_element))
try:
alert_element = module_element.find_element_by_class_name(
'alert')
if alert_element:
raise ClipBucketModuleError(alert_element.text)
except exceptions.NoSuchElementException:
# Lack of alert is good: the module is installed correctly.
continue
logger.info('Module check complete')
def deselect_by_index(self,and not merely by counting.
:Args:
- index - The option at this index will be deselected
throws NoSuchElementException If there is no option with specisied index in SELECT
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
for opt in self.options:
if opt.get_attribute("index") == str(index):
self._unsetSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index)
def deselect_by_visible_text(self, text):
"""deselect all options that display text matching the argument. That is,when given "Bar" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- text - The visible text to match against
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect options of a multi-select")
matched = False
xpath = ".//option[normalize-space(.) = %s]" % self._escapestring(text)
opts = self._el.find_elements(By.XPATH, xpath)
for opt in opts:
self._unsetSelected(opt)
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with visible text: %s" % text)
def _get_Feed_post_media(post): # Todo: refactor searching image
"""
Get link to post from post web-element from Feed
:param post:
:return:
"""
try:
image = post.find_element_by_css_selector('div:nth-child(2) img')
return image.get_attribute('src')
except excp.NoSuchElementException:
pass
try:
video = post.find_element_by_tag_name('video')
return video.get_attribute('src')
except excp.NoSuchElementException:
pass
return False
def select_by_index(self,and not merely by counting.
:Args:
- index - The option at this index will be selected
"""
match = str(index)
matched = False
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
if not self.is_multiple:
return
matched = True
if not matched:
raise NoSuchElementException("Could not locate element with index %d" % index)
def test_static_placeholders_permissions(self):
username = getattr(self.user, get_user_model().USERNAME_FIELD)
password = username
self._fastlogin(username=username, password=password)
pk = Placeholder.objects.filter(slot='logo').order_by('id')[0].pk
placeholder_name = 'cms-placeholder-%s' % pk
# test static placeholder permission (content of static placeholders is NOT editable)
self.driver.get('%s/en/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
self.assertRaises(NoSuchElementException, self.driver.find_element_by_class_name, placeholder_name)
# update userpermission
edit_permission = Permission.objects.get(codename="edit_static_placeholder")
self.user.user_permissions.add( edit_permission )
# test static placeholder permission (content of static placeholders is editable)
self.driver.get('%s/en/?%s' % (self.live_server_url, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')))
self.assertTrue(self.driver.find_element_by_class_name(placeholder_name))
def repeat_next(self):
while True:
try:
next_button = self.wait.until(
EC.element_to_be_clickable(
(By.CLASS_NAME, 'float-right'))
)
pages = self.driver.find_elements(By.CSS_SELECTOR, '.current.reference.internal')
for page in pages:
("\n" + page.get_attribute('text'))
self.click(next_button)
except NoSuchElementException:
print("End of page")
break
except TimeoutException:
print("Timeout error...")
break
def wait_and_find(driver, locator_type, timeout=3, check_iframes=True):
if is_found(driver, timeout):
return driver.find_element(locator_type, locator)
else:
if check_iframes: # this may return the browser with an iframe active
driver.switch_to_default_content()
iframes = driver.find_elements_by_tag_name('iframe')
for iframe in iframes:
driver.switch_to_default_content()
driver.switch_to_frame(iframe)
if is_found(driver, timeout=0):
return driver.find_element(locator_type, locator)
# If we get here,search also fails in iframes
driver.switch_to_default_content()
raise NoSuchElementException("Element not found during wait_and_find")