def find_draft(assignment_type, is_all):
"""
assignment_type: can be "reading", "homework", "external" or "event"
is_all: boolean value
True when you want to find all assignment of assignment_type
"""
if is_all:
draft = teacher.find_all(
By.XPATH,
'//div[@data-assignment-type="' + assignment_type + '"'
' and not(contains(@class, "is-published")) and not(@draggable="true")]'
)
else:
draft = teacher.find(
By.XPATH,
'//div[@data-assignment-type="' + assignment_type + '"'
' and not(contains(@class, "is-published")) and not(@draggable="true")]'
)
return draft
python类XPATH的实例源码
def find_element_by_xpath(self, xpath):
"""Finds element by xpath.
:Args:
xpath - xpath of element to locate. "//input[@class='myelement']"
Note: The base path will be relative to this element's location.
This will select the first link under this element.
::
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
::
myelement.find_elements_by_xpath("//a")
"""
return self.find_element(by=By.XPATH, value=xpath)
def find_elements_by_xpath(self, xpath):
"""Finds elements within the element by xpath.
:Args:
- xpath - xpath locator string.
Note: The base path will be relative to this element's location.
This will select all links under this element.
::
myelement.find_elements_by_xpath(".//a")
However, this will select all links in the page itself.
::
myelement.find_elements_by_xpath("//a")
"""
return self.find_elements(by=By.XPATH, value=xpath)
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 operation(self,vmname,btnlocator,statelocator,text,user):
#?????
#name?????????????
#btnlocator????????????????????xpath
#statelocator???xpath
#text????????????????
if 'stop' in btnlocator:
Cloud_DebugLog.stepinfo(Messages.VM_STOP)
elif 'restart' in btnlocator:
Cloud_DebugLog.stepinfo(Messages.VM_RESTART)
else:
Cloud_DebugLog.stepinfo(Messages.VM_START)
userid=utils_misc.readconfig("DepManage").get(user, 'userid')
password=utils_misc.readconfig("DepManage").get(user, 'password')
#userid=utils_misc.readconfig("DepManage").get('USER', 'userid')
#password=utils_misc.readconfig("DepManage").get('USER', 'password')
#self.normal_cloud_login(userid,password)
self._search(vmname)
Cloud_server_map=self.Cloud_server_map
Cloud_server_map.getelement(btnlocator).click()
Cloud_server_map.getelement(Cloud_server_map.submit_btn).click()
WebDriverWait(self.Cloud_client_browser,100).until(expected_conditions.text_to_be_present_in_element((By.XPATH,statelocator), text))
Cloud_DebugLog.stepinfo(Messages.VM_operation)
def change_vm_size(self,vmname,cpu_size,memory_size,powervm_cpu_units='',flavor_options=''):
Cloud_DebugLog.stepinfo(Messages.VM_RESIZE)
self._search(vmname)
Cloud_server_map=self.Cloud_server_map
Cloud_server_map.getelement(name=Cloud_server_map.change_vm_size).click()
#Cloud_server_map.get_select(flavor_options,id=Cloud_server_map.flavor_options_id)
Cloud_server_map.getelement(name=Cloud_server_map.cpu_size).clear()
Cloud_server_map.getelement(name=Cloud_server_map.cpu_size).send_keys(cpu_size)
# Cloud_server_map.getelement(name=Cloud_server_map.cpu_units).clear()
# Cloud_server_map.getelement(name=Cloud_server_map.cpu_units).send_keys(cpu_units)
Cloud_server_map.getelement(name=Cloud_server_map.memory_size).clear()
Cloud_server_map.getelement(name=Cloud_server_map.memory_size).send_keys(memory_size)
Cloud_server_map.getelement(id=Cloud_server_map.change_size_button_id).click()
WebDriverWait(self.Cloud_server_map,100).until_not(lambda x: x.getelement(name=Cloud_server_map.memory_size).is_displayed())
self._search(vmname)
#Cloud_server_map.getelement(name=Cloud_server_map.change_vm_size).click()
#memory=(Cloud_server_map.getelement('//*[@id="product-page"]/div[3]/table/tbody/tr/td[7]').text).split('/')[1]
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.cpu_size_xpath), cpu_size))
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.memory_size_xpath), memory_size+'GB'))
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.state_pass), '??'))
Cloud_DebugLog.stepinfo(Messages.VM_RESIZE_VERIFY)
def operation(self,vmname,btnlocator,statelocator,text,user):
#?????
#name?????????????
#btnlocator????????????????????xpath
#statelocator???xpath
#text????????????????
if 'stop' in btnlocator:
Cloud_DebugLog.stepinfo(Messages.VM_STOP)
elif 'restart' in btnlocator:
Cloud_DebugLog.stepinfo(Messages.VM_RESTART)
else:
Cloud_DebugLog.stepinfo(Messages.VM_START)
userid=utils_misc.readconfig("DepManage").get(user, 'userid')
password=utils_misc.readconfig("DepManage").get(user, 'password')
#userid=utils_misc.readconfig("DepManage").get('USER', 'userid')
#password=utils_misc.readconfig("DepManage").get('USER', 'password')
#self.normal_cloud_login(userid,password)
self._search(vmname)
Cloud_server_map=self.Cloud_server_map
Cloud_server_map.getelement(btnlocator).click()
Cloud_server_map.getelement(Cloud_server_map.submit_btn).click()
WebDriverWait(self.Cloud_client_browser,100).until(expected_conditions.text_to_be_present_in_element((By.XPATH,statelocator), text))
Cloud_DebugLog.stepinfo(Messages.VM_operation)
def change_vm_size(self,vmname,cpu_size,memory_size,powervm_cpu_units='',flavor_options=''):
Cloud_DebugLog.stepinfo(Messages.VM_RESIZE)
self._search(vmname)
Cloud_server_map=self.Cloud_server_map
Cloud_server_map.getelement(name=Cloud_server_map.change_vm_size).click()
#Cloud_server_map.get_select(flavor_options,id=Cloud_server_map.flavor_options_id)
Cloud_server_map.getelement(name=Cloud_server_map.cpu_size).clear()
Cloud_server_map.getelement(name=Cloud_server_map.cpu_size).send_keys(cpu_size)
# Cloud_server_map.getelement(name=Cloud_server_map.cpu_units).clear()
# Cloud_server_map.getelement(name=Cloud_server_map.cpu_units).send_keys(cpu_units)
Cloud_server_map.getelement(name=Cloud_server_map.memory_size).clear()
Cloud_server_map.getelement(name=Cloud_server_map.memory_size).send_keys(memory_size)
Cloud_server_map.getelement(id=Cloud_server_map.change_size_button_id).click()
WebDriverWait(self.Cloud_server_map,100).until_not(lambda x: x.getelement(name=Cloud_server_map.memory_size).is_displayed())
self._search(vmname)
#Cloud_server_map.getelement(name=Cloud_server_map.change_vm_size).click()
#memory=(Cloud_server_map.getelement('//*[@id="product-page"]/div[3]/table/tbody/tr/td[7]').text).split('/')[1]
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.cpu_size_xpath), cpu_size))
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.memory_size_xpath), memory_size+'GB'))
WebDriverWait(self.Cloud_client_browser,200).until(expected_conditions.text_to_be_present_in_element((By.XPATH,Cloud_server_map.state_pass), '??'))
Cloud_DebugLog.stepinfo(Messages.VM_RESIZE_VERIFY)
def menu_image(self):
Cloud_DebugLog.stepinfo(Messages.IMAGE_LIST)
Cloud_DebugLog.debug_print(Messages.IMAGE_LIST)
menuname = 'image'
Cloud_client_browser = self.driver
#Cloud_image_map = Image_UIMap(Cloud_client_browser)
Cloud_browser_main_map = Main_Browser_UIMap(Cloud_client_browser)
#image_map=image_UIMap(Cloud_client_browser)
#Left_Menu().menu_workorder(self.driver, menuname)
Cloud_browser_main_map.get_menu('image').click()
locator = (By.XPATH,"//a[@href='/image/']")
#flag=WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
try:
WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
except:
print '??????????????????'
Cloud_browser_main_map.get_menu('image').click()
Cloud_browser_main_map.get_menu('image/').click()
def menu_image(self):
Cloud_DebugLog.stepinfo(Messages.IMAGE_LIST)
Cloud_DebugLog.debug_print(Messages.IMAGE_LIST)
menuname = 'image'
Cloud_client_browser = self.driver
#Cloud_image_map = Image_UIMap(Cloud_client_browser)
Cloud_browser_main_map = Main_Browser_UIMap(Cloud_client_browser)
#image_map=image_UIMap(Cloud_client_browser)
#Left_Menu().menu_workorder(self.driver, menuname)
Cloud_browser_main_map.get_menu('image').click()
locator = (By.XPATH,"//a[@href='/image/']")
#flag=WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
try:
WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
except:
print '??????????????????'
Cloud_browser_main_map.get_menu('image').click()
Cloud_browser_main_map.get_menu('image/').click()
def menu_custom_image(self):
Cloud_DebugLog.stepinfo(Messages.IMAGE_LIST)
Cloud_DebugLog.debug_print(Messages.IMAGE_LIST)
Cloud_client_browser = self.driver
Cloud_image_map = Image_UIMap(Cloud_client_browser)
Cloud_browser_main_map = Main_Browser_UIMap(Cloud_client_browser)
#image_map=image_UIMap(Cloud_client_browser)
#Left_Menu().menu_workorder(self.driver, menuname)
Cloud_browser_main_map.get_menu('image').click()
locator = (By.XPATH,"(//a[@href='/image/'])[2]")
#flag=WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
try:
WebDriverWait(self.driver,5).until(EC.visibility_of_element_located(locator))
except:
print '?????????????????????'
Cloud_browser_main_map.get_menu('image').click()
time.sleep(2)
Cloud_image_map.getelement("(//a[@href='/image/'])[2]").click()
def get_info(self,id):
'''???????????????????????????????'''
dic = {}
url = 'https://detail.tmall.hk/hk/item.htm?spm=a220o.1000855.1998025129.2.102f616emYvWTL&abtest=_AB-LR32-PR32&pvid=a2be15e3-8200-46b3-bd09-de041b8b8dc3&pos=2&abbucket=_AB-M32_B9&acm=03054.1003.1.2431317&id={}&scm=1007.12144.81309.23864_0&sku_properties=-1:-1'.format(id)
self.driver.get(url)
# html = self.driver.page_source
# print(html)
try:
location = self.waiter.until(
EC.presence_of_element_located((By.XPATH,'//dl[@class="tm-happy11-panel"]/dd/span[@class="tm-price"]'))
)
info = location.text.strip()
dic['id'] = id
dic['price'] = info if info else '?????'
self.write_info(dic)
except TimeoutException as e:
print(e)
dic['id'] = id
dic['price'] = '{}????????'.format(e).strip()
self.write_info(dic)
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 build(self, selectors):
adjacent = selectors.pop('adjacent', None)
xpath = self._process_adjacent(adjacent) if adjacent else './/'
xpath += selectors.pop('tag_name', '*')
index = selectors.pop('index', None)
# the remaining entries should be attributes
if selectors:
xpath += '[{}]'.format(self.attribute_expression(None, selectors))
if adjacent and index is not None:
xpath += "[{}]".format(index + 1)
logging.debug({'xpath': xpath, 'selectors': selectors})
return [By.XPATH, xpath]
# TODO: Get rid of building
def test_handles_custom_attributes(self, browser, mocker, expect_one, expect_all):
div1 = element(mocker, values={'tag_name': 'div'}, attrs={'custom_attribute': 'foo'})
span = element(mocker, values={'tag_name': 'span'}, attrs={'custom_attribute': 'foo'})
div2 = element(mocker, values={'tag_name': 'div'}, attrs={'custom_attribute': 'foo'})
expect_one.return_value = span
expect_all.return_value = [div1, span, div2]
selector = {'custom_attribute': 'foo', 'tag_name': 'span'}
result = locate_one(browser, selector)
expect_one.assert_called_once_with(By.XPATH, ".//span[@custom-attribute='foo']")
assert result.tag_name == 'span'
# with special cased selectors
def get_second_column_values(self, elem, flight_dict):
has_wifi = False
second_col_elems = elem.find_elements(
By.XPATH, self.REL_PATHS['SECOND_COL'])
if len(second_col_elems) > 2:
has_wifi = True
second_col_elems.pop(0)
flight_dict['dep_hours'] = second_col_elems[0].find_element(
By.XPATH, self.REL_PATHS['DEP_HOURS']).get_attribute('tooltip')
flight_dict['arr_hours'] = second_col_elems[0].find_element(
By.XPATH, self.REL_PATHS['ARR_HOURS']).get_attribute('tooltip')
flight_dict['airline'] = second_col_elems[1].find_element(
By.XPATH, self.REL_PATHS['AIRLINE']).text
flight_dict['has_wifi'] = has_wifi
return flight_dict
def finish_new_topic(self):
free_topic_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dt/span[1]') # '????'????
encrypt_topic_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dt/span[2]') # '????'????
charge_topic_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dt/span[3]') # '????'????
topic_present_page_switch_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dd/div[1]/div[2]/span[1]/span') # '?????'??
encrypt_input_box_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dd/div[2]/div/input') # ????'?????'??
charge_input_box_loc = (By.XPATH, r'/html/body/div[1]/div[2]/dl/dd/div[3]/div/span[2]/input') # ????'?????'??
new_topic_finish_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/div/a[2]') # ????'??'????
new_topic_previous_btn_loc = (By.XPATH, r'/html/body/div[1]/div[2]/div/a[1]') # ????'???'????
self.loc_element(*free_topic_btn_loc).click() # ??'????'??
self.loc_element(*topic_present_page_switch_btn_loc).click() # ??'?????'
self.loc_element(*new_topic_finish_btn_loc).click() # ??'??'??
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 _get_link(self, the_link, link_type, link_text):
try:
links = self.pydriver.find_elements(By.XPATH, "//%s" % the_link)
except (NoSuchElementException, StaleElementReferenceException, WebDriverException), e:
ACLogger.log_and_print_error(
'_get_link: unable to find type(%s) links in UI, exception=%s' % (link_type, str(e)))
return False
clicked_it = False
for link in links:
if clicked_it is False and link.text == link_text:
try:
link.click()
except (NoSuchElementException, StaleElementReferenceException, WebDriverException), e:
ACLogger.log_and_print_error(
'_get_link: unable to click on type(%s) text(%s) in UI, exception=%s' % (link_type,link_text,str(e)))
return False
finally:
clicked_it = True
break
if clicked_it is False:
ACLogger.log_and_print_error(
'_get_link: unable to find link %s in UI ' % link_text)
return False
time.sleep(2)
return True
def find_element_by_xpath(self, xpath):
"""Finds element by xpath.
:Args:
xpath - xpath of element to locate. "//input[@class='myelement']"
Note: The base path will be relative to this element's location.
This will select the first link under this element.
::
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
::
myelement.find_elements_by_xpath("//a")
"""
return self.find_element(by=By.XPATH, value=xpath)