def wait_for_presence(self, selector='', **kwargs):
'''
Wait for an element to be present. (Does not need to be visible.)
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.presence_of_element_located((by, selector)) or
EC.presence_of_elements_located((by, selector)),
**kwargs)
python类CSS_SELECTOR的实例源码
def wait_for_clickable(self, selector='', **kwargs):
'''
Wait for an element to be clickable.
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.element_to_be_clickable((by, selector)), **kwargs)
def wait_for_visible(self, selector='', **kwargs):
'''
Wait for an element to be visible.
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.visibility_of_element_located((by, selector)),
**kwargs)
def wait_for_invisible(self, selector='', **kwargs):
'''
Wait for an element to be invisible.
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.invisibility_of_element_located((by, selector)),
**kwargs)
def wait_for_text(self, selector='', text='', **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.
text: str
The string to look for. This must be precise.
(Case, punctuation, UTF characters... etc.)
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.text_to_be_present_in_element((by, selector),
text), **kwargs)
def wait_for_selected(self, selector='', selected=True, **kwargs):
'''
Wait for an element (checkbox/radio) to be selected.
Parameters
----------
selector: str
A CSS selector to search for. This can be any valid CSS selector.
selected: bool
Whether or not the element should be selected. Default True
kwargs:
Passed on to _wait_for
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.element_located_selection_state_to_be((by, selector),
selected), **kwargs)
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
'''
if selector.startswith('/'):
by = By.XPATH
else:
by = By.CSS_SELECTOR
self._wait_for(EC.text_to_be_present_in_element_value((by, selector),
value), **kwargs)
def _find_next_page_element(self):
"""Finds the element that locates the next page for any search engine.
Returns:
The element that needs to be clicked to get to the next page or a boolean value to
indicate an error condition.
"""
if self.search_type == 'normal':
selector = self.next_page_selectors[self.search_engine_name]
try:
# wait until the next page link is clickable
WebDriverWait(self.webdriver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, selector)))
except (WebDriverException, TimeoutException):
self._save_debug_screenshot()
# raise Exception('{}: Cannot locate next page element: {}'.format(self.name, str(e)))
try:
return self.webdriver.find_element_by_css_selector(selector)
except Exception:
logger.error('failed find_element_by_css_selector, sleep 30 sec')
time.sleep(30)
pass
elif self.search_type == 'image':
self.page_down()
if self.search_engine_name == 'google':
return self.webdriver.find_element_by_css_selector('input._kvc')
else:
return True
def test_basic_inventory(self):
ui_test_banner()
driver = self.init_driver()
self.login(driver)
assert self.click_button(driver, "Devices")
authorized_device = self.wait_for_element(driver, By.CSS_SELECTOR, "div.rightFluid.padding-right tbody.clickable > tr")
assert authorized_device
authorized_device.click()
assert "vexpress-qemu" in authorized_device.text
assert "mender-image-master" in authorized_device.text
# make sure basic inventory items are there
assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'Linux version')]")
assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'eth0')]")
assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'ARM')]")
ui_test_success()
self.destroy_driver(driver)
def test_deployment_in_progress(self):
ui_test_banner()
driver = self.init_driver()
self.login(driver)
assert self.click_button(driver, "Deployments")
timeout = time.time() + 60*5
while time.time() < timeout:
e = self.wait_for_element(driver, By.CSS_SELECTOR, "span.status.inprogress")
if e.text == '1':
break
time.sleep(1)
else:
raise Exception("Deployment never in progress")
ui_test_success()
self.destroy_driver(driver)
def test_deployment_successful(self):
ui_test_banner()
driver = self.init_driver()
self.login(driver)
assert self.click_button(driver, "Deployments")
timeout = time.time() + 60*5
while time.time() < timeout:
e = self.wait_for_element(driver, By.CSS_SELECTOR, "span.status.success")
if e.text == '1':
break
time.sleep(1)
else:
raise Exception("Deployment never completed")
ui_test_success()
self.destroy_driver(driver)
def view_volume(self, name):
row = self._get_row_with_volume_name(name)
name_link = row.cells['name'].find_element(by.By.CSS_SELECTOR, 'a')
name_link.click()
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 test_profile_navigation(self, browser, base_test_data):
"""
Nothing should break when navigating to the profile and back to learners search page
"""
create_enrolled_user_batch(2, program=base_test_data.program, is_staff=False)
browser.get("/learners")
browser.click_when_loaded(By.CLASS_NAME, 'menu-icon')
browser.wait().until(
lambda driver: "open" in driver.find_element_by_class_name('nav-drawer').get_attribute('class')
)
browser.click_when_loaded(By.CSS_SELECTOR, 'a .profile-image')
browser.wait_until_loaded(By.CLASS_NAME, 'user-page')
# Go back to learners
browser.click_when_loaded(By.CLASS_NAME, 'menu-icon')
browser.wait().until(
lambda driver: "open" in driver.find_element_by_class_name('nav-drawer').get_attribute('class')
)
browser.click_when_loaded(By.CSS_SELECTOR, "a[href='/learners']")
browser.wait_until_loaded(By.CLASS_NAME, 'learner-results')
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
"""
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 goto_course_list(self):
"""Go to the course picker."""
long_wait = WebDriverWait(self.driver, 30)
try:
long_wait.until(
expect.presence_of_element_located(
(By.ID, 'ox-react-root-container')
)
)
if 'tutor' in self.current_url():
self.find(By.CSS_SELECTOR, '.ui-brand-logo').click()
self.page.wait_for_page_load()
else:
raise HTTPError('Not currently on an OpenStax Tutor webpage:' +
'%s' % self.current_url())
except Exception as ex:
raise ex
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 goto_calendar(self):
"""Return the teacher to the calendar dashboard."""
print('Enter: goto_calendar')
try:
print('Try to return to the calendar')
self.find(By.CSS_SELECTOR, '.course-name').click()
print('Succeeded')
self.page.wait_for_page_load()
except:
print('Failed, Try to return to the calendar using the Brand')
try:
self.find(
By.CSS_SELECTOR,
'.brand'
).click()
print('Succeeded')
self.page.wait_for_page_load()
except:
print('Failed, Load manually')
self.get(
'https://' +
'/'.join(self.driver.current_url.split('/')[2:5])
)
pass
print('Exit: goto_calendar')
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 _given_xpath_or_css(self, selector):
xpath = selector.pop('xpath', None)
css = selector.pop('css', None)
if not (xpath or css):
return None
if xpath and css:
raise ValueError("'xpath' and 'css' cannot be combined ({})".format(selector))
how, what = [None] * 2
if xpath:
how = By.XPATH
what = xpath
elif css:
how = By.CSS_SELECTOR
what = css
if selector and not self._can_be_combined_with_xpath_or_css(selector):
raise ValueError('{} cannot be combined with other selectors {})'.format(how, selector))
return [how, what]
def find_element(self, by=By.ID, value=None):
if not By.is_valid(by) or not isinstance(value, str):
raise InvalidSelectorException("Invalid locator values passed in")
if self._w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self._execute(Command.FIND_CHILD_ELEMENT,
{"using": by, "value": value})['value']
def find_elements(self, by=By.ID, value=None):
if not By.is_valid(by) or not isinstance(value, str):
raise InvalidSelectorException("Invalid locator values passed in")
if self._w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self._execute(Command.FIND_CHILD_ELEMENTS,
{"using": by, "value": value})['value']
def find_element(self, by=By.ID, value=None):
"""
'Private' method used by the find_element_by_* methods.
:Usage:
Use the corresponding find_element_by_* instead of this.
:rtype: WebElement
"""
if not By.is_valid(by) or not isinstance(value, str):
raise InvalidSelectorException("Invalid locator values passed in")
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self.execute(Command.FIND_ELEMENT,
{'using': by, 'value': value})['value']
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
"""
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 wait_for_visibility(
driver: webdriver, *, by_css: str = None,
by_id: str = None, time_to_wait: int = 5):
"""Wait until element is visible.
:param driver: Selenium driver
:param by_css: CSS selector to locate the element to wait for
:param by_id: ID of the element to wait for
:param time_to_wait: maximum number of seconds to wait
"""
assert by_id or by_css, "Provide ID or CSS selector"
if by_css:
by_locator = (By.CSS_SELECTOR, by_css)
else:
by_locator = (By.ID, by_id)
WebDriverWait(driver, time_to_wait).until(
expected_conditions.visibility_of_element_located(by_locator))
def shot_campaign(live_server, organizer, event, logged_in_client, campaign_web, campaign_twitter, orders, clicks):
event.plugins += ',pretix_campaigns'
event.save()
logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/'.format(
organizer.slug, event.slug
))
screenshot(logged_in_client, 'website/control/campaigns_list.png')
logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/'.format(
organizer.slug, event.slug, campaign_twitter.code
))
WebDriverWait(logged_in_client, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#cbd_chart svg"))
)
time.sleep(.5)
screenshot(logged_in_client, 'website/control/campaigns_detail.png')
def shot_campaign(live_server, organizer, event, logged_in_client, campaign_web, campaign_twitter, orders, clicks):
event.plugins += ',pretix_campaigns'
event.save()
logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/'.format(
organizer.slug, event.slug
))
screenshot(logged_in_client, 'plugins/campaigns/list.png')
logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/edit'.format(
organizer.slug, event.slug, campaign_twitter.code
))
screenshot(logged_in_client, 'plugins/campaigns/edit.png')
logged_in_client.get(live_server.url + '/control/event/{}/{}/campaigns/{}/'.format(
organizer.slug, event.slug, campaign_twitter.code
))
WebDriverWait(logged_in_client, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#cbd_chart svg"))
)
time.sleep(.5)
screenshot(logged_in_client, 'plugins/campaigns/stats.png')
def _goto_next_page(self):
"""
Click the next page element,
Returns:
The url of the next page or False if there is no such url
(end of available pages for instance).
"""
next_url = ''
element = self._find_next_page_element()
if hasattr(element, 'click'):
next_url = element.get_attribute('href')
try:
element.click()
except WebDriverException:
# See http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error
# first move mouse to the next element, some times the element is not visibility
selector = self.next_page_selectors[self.search_engine_name]
if selector:
try:
next_element = WebDriverWait(self.webdriver, 5).until(
EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
webdriver.ActionChains(self.webdriver).move_to_element(next_element).perform()
# wait until the next page link emerges
WebDriverWait(self.webdriver, 8).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, selector)))
element = self.webdriver.find_element_by_css_selector(selector)
next_url = element.get_attribute('href')
element.click()
except WebDriverException:
pass
# wait until the next page was loaded
if not next_url:
return False
else:
return next_url
def choose_folder(self, folder_name):
folder = self.is_object_present(folder_name)
folder_link = folder.cells[0].find_element(By.CSS_SELECTOR, 'a')
folder_link.click()
self._wait_until(lambda _: self.objects_table.is_empty)