Python selenium.webdriver.common.by.By 模块,XPATH 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用selenium.webdriver.common.by.By.XPATH。
def get_element(self, selector):
'''
Gets element by CSS selector.
Parameters
----------
selector: str
A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.
Returns
-------
selenium.webdriver.remote.webelement.WebElement
A selenium element object.
'''
elem = self.find_element(selector)
if elem:
return WebRunnerElement(elem._parent, elem._id, elem._w3c)
else:
raise NoSuchElementException
def verify_user_logged_in(selenium):
# kdyz potrebujeme otestovat,ze na strance je nejaky konkretni element
# el = selenium.find_element_by_xpath('//*[@id="messages"]/div/div')
# vynechame nefunkcni identifikatory pro pripad,ze se zmeni HTML sablona
el = selenium.find_element_by_id('messages')
# kdyz potrebujeme zjistit,ze element obsahuje konkretni text
assert 'Welcome back' in el.text
# # ExplicitWait - kdyz se nahravaji veci pomoci JavaScriptu a nereloadne se cela stranka
# webdriverwait(selenium,2).until(
# EC.text_to_be_present_in_element((By.XPATH,'//*[@id="messages"]/div/div'),'Welcome back')
# )
# # kdyz potrebujeme otestovat,ze na strance neco neni
# from selenium.common import exceptions
# with pytest.raises(exceptions.NoSuchElementException,message='UNEXPECTED ELEMENT PRESENT'):
# # musi hodit vyjimku,jinak Failed
# selenium.find_element_by_xpath('//*[@id="messages"]/div/div')
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 find_element(self, selector):
'''
Finds an element by CSS/XPATH selector.
Parameters
----------
selector: str
A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.
Returns
-------
selenium.webdriver.remote.webelement.WebElement or None
Returns an element or nothing at all
'''
elem = None
try:
if selector.startswith('/'):
elem = self.browser.find_element_by_xpath(selector)
else:
elem = self.browser.find_element_by_css_selector(selector)
except NoSuchElementException:
pass
return elem
def find_elements(self, selector):
'''
Finds elements by CSS/XPATH selector.
Parameters
----------
selector: str
A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.
Returns
-------
list of selenium.webdriver.remote.webelement.WebElement or list
Returns a list of elements or empty list
'''
elems = []
try:
if selector.startswith('/'):
elems = self.browser.find_elements_by_xpath(selector)
else:
elems = self.browser.find_elements_by_css_selector(selector)
except NoSuchElementException:
pass
return elems
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)
def wait_for_visible(self, **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,
**kwargs)
def wait_for_invisible(self, **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,
**kwargs)
def wait_for_text(self, 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_text_in_value(self, **kwargs):
'''
Wait for an element's value 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,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,
text), **kwargs)
def wait_for_selected(self, 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,
selected), **kwargs)
def login(self, driver):
if "login" not in driver.current_url:
return
mock_email = auth.email
mock_password = auth.password
print("Logging in with credentials:")
print("Email: " + mock_email)
print("Password: " + mock_password)
email_field = driver.find_element_by_id("email")
email_field.click()
email_field.send_keys(mock_email)
password_field = driver.find_element_by_id("password")
password_field.click()
password_field.send_keys(mock_password)
clicked = self.click_button(driver, "log in")
if not clicked:
clicked = self.click_button(driver, "create user")
assert clicked
xp = tag_contents_xpath("button", "Dashboard")
element = self.wait_for_element(driver, By.XPATH, xp)
assert element
def test_authorize_all(self):
ui_test_banner()
driver = self.init_driver()
self.login(driver)
assert self.click_button(driver, "Devices")
self.click_button(driver, "Authorize 1 device", timeout=600)
xp = "//table/tbody[@class='clickable']/tr/td[3]/div"
authorized_device = self.wait_for_element(driver, xp, timeout=600)
assert authorized_device
authorized_device.click()
timeout = time.time() + (60*5)
while time.time() < timeout:
time.sleep(0.2)
if self.wait_for_element(driver, xp).text == "vexpress-qemu":
break
else:
raise Exception("Device never appeared for authorization")
print("Found authorized_device: '" + authorized_device.text + "'")
assert authorized_device.text == "vexpress-qemu"
ui_test_success()
self.destroy_driver(driver)
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, "//*[contains(text(),'Linux version')]")
assert self.wait_for_element(driver,'eth0')]")
assert self.wait_for_element(driver,'ARM')]")
ui_test_success()
self.destroy_driver(driver)
def validateLink(self, url, expectedText = None, expectedTitle = None, expectedUrl = None, \
xpathContext = None):
xpathContext = xpathContext if xpathContext else ""
selector = ".//{1}a[@href='{0}']".format(url, xpathContext)
if expectedText:
self.assertTextPresent(By.XPATH, selector, expectedText)
totalTries = self._followLinkMaxRetries + 1
for i in range(0, totalTries):
try:
self.click(By.XPATH, "Click {0}".format(expectedText), \
expectedURL = expectedUrl if expectedUrl else url)
break
except TimeoutException:
retry = i + 1 # First 'try' is not a retry
if retry < totalTries:
pass
if expectedTitle:
self.assertTitle(expectedTitle);
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 click_page():
driver = webdriver.Firefox()
driver.get('http://yidao620c.github.io/archives/')
driver.maximize_window()
len1 = len(driver.find_elements_by_xpath(
'//div[@class="post-archive"]/ul[@class="listing"]/li/a'))
_log.info('????????...')
for k in range(1, 100):
logging.info('?{}???...'.format(k))
for i in range(0, len1):
l_xpath = '(//div[@class="post-archive"]/ul[@class="listing"]/li/a)[{}]'.format(i + 1)
ele = webdriverwait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, l_xpath))
)
ele.click()
driver.back()
_log.info('all finished.')
driver.close()
def _click_page(total_posts, pool_size, group_index):
_log.info('?{}?: starting...'.format(group_index + 1))
if group_index > 0 and total_posts < pool_size * group_index:
return
# ????????
_driver = webdriver.PhantomJS()
_driver.get('https://www.xncoding.com/archives/')
global TRY_COUNT
for k in range(1, TRY_COUNT + 1):
# _log.info('?{}?: ?{}???...'.format(group_index + 1,k))
for i in range(pool_size * group_index, min(pool_size * (group_index + 1), total_posts)):
l_xpath = '(//article/header/h1[@class="post-title"]/a[@class="post-title-link"])[{}]'.format(i + 1)
ele = webdriverwait(_driver, l_xpath))
)
ele.click()
webdriverwait(_driver, 5).until(
EC.presence_of_element_located((By.XPATH, '//div[@class="post-body"]'))
)
_driver.back()
_log.info('?{}?: finished.'.format(group_index + 1))
_driver.close()
def just_click():
# ????????
_driver = webdriver.PhantomJS()
_driver.get('https://www.xncoding.com/archives/')
# driver.maximize_window()
posts_count = len(_driver.find_elements_by_xpath(
'//article/header/h1[@class="post-title"]/a[@class="post-title-link"]'))
for cc in range(1, posts_count + 1):
l_xpath = '(//article/header/h1[@class="post-title"]/a[@class="post-title-link"])[{}]'.format(cc)
ele = webdriverwait(_driver, 10).until(
EC.element_to_be_clickable((By.XPATH, l_xpath))
)
_log.info('???{}???'.format(cc))
ele.click()
webdriverwait(_driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//div[@class="post-body"]'))
)
_driver.back()
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 url_fetch(self, keys, critical, fetch_repeat):
try:
logging.warning("-------------------------------")
if keys[0] == "detail":
logging.warning("fetch %s", url)
x_str = "//*[@id='detail'][contains(@isloaded,'1')]"
self.driver.get(url)
element_present = EC.presence_of_element_located((By.XPATH, x_str))
webdriverwait(self.driver, 60).until(element_present)
except:
logging.warning("Unexpected error: %s", sys.exc_info()[0])
#self.clear_session()
return 0, ""
response = self.driver.page_source
if not response:
logging.warning("not response %s", response)
return 0, ""
logging.warning("fetch done!")
return 1, response
def get_total_page(browser, url):
browser.get(url)
try:
time.sleep(4)
total_room = browser.find_element_by_xpath('/html/body/div[4]/div[1]/div[2]/h2/span').text
if not total_room:
return None
if int(total_room) <= 30:
return 1
total = webdriverwait(browser, 30).until(
EC.presence_of_element_located((By.XPATH, "/html/body/div[4]/div[1]/div[7]/div[2]/div/a[last()]"))
)
if not total.text.isdigit():
total_page = browser.find_element_by_xpath('/html/body/div[4]/div[1]/div[7]/div[2]/div/a[last()-1]').text
else:
total_page = total.text
return total_page
except TimeoutException as e:
print('????????25??????')
time.sleep(25)
return get_total_page(url)
def step_03_check_basket_is_empty(selenium):
# //*[@id="messages"]/div[2]/p
# pytest.set_trace()
# el = selenium.find_element_by_id('messages')
# import time
# time.sleep(1)
# assert 'Your basket is Now empty' in el.text
webdriverwait(selenium, 2).until(
EC.text_to_be_present_in_element(
# (By.ID,'messages'),
(By.XPATH, '//p[contains(text(),"Your basket is Now empty")]'),
'Your basket is Now empty'
)
)
# empty_alert = selenium.find_element(By.XPATH,'//p[contains(text(),"Your basket is Now empty")]')
def setUp(self):
"""Pretest settings."""
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.teacher = Teacher(
use_env_vars=True,
pasta_user=self.ps,
capabilities=self.desired_capabilities
)
else:
self.teacher = Teacher(
use_env_vars=True
)
self.teacher.login()
# go to student scores
self.teacher.select_course(appearance='college_physics')
self.teacher.driver.find_element(
By.LINK_TEXT, 'Student scores').click()
self.teacher.wait.until(
expect.visibility_of_element_located(
(By.XPATH, '//span[contains(text(),"Student scores")]')
)
).click()
def setUp(self):
"""Pretest settings."""
self.ps = PastaSauce()
self.desired_capabilities['name'] = self.id()
if not LOCAL_RUN:
self.student = Student(
use_env_vars=True,
capabilities=self.desired_capabilities
)
else:
self.student = Student(
use_env_vars=True
)
self.student.login()
self.student.select_course(title='College Physics with Courseware')
self.wait = webdriverwait(self.student.driver, Assignment.WAIT_TIME)
self.wait.until(
expect.visibility_of_element_located((
By.XPATH,
'//button[contains(@class,"practice")]'
))
).click()
self.wait = webdriverwait(self.student.driver, Assignment.WAIT_TIME)
self.student.login()
def delete_assignment(target_element, is_published):
"""
target_element: the web element of assignment to be deleted
"""
target_element.click()
sleep(1)
if is_published:
teacher.find(
By.ID, "edit-assignment-button"
).click()
sleep(1)
delete_button = teacher.wait.until(
expect.element_to_be_clickable(
(By.XPATH, '//button[contains(@class,"delete-link")]')
)
)
teacher.scroll_to(delete_button)
sleep(1)
delete_button.click()
teacher.find(
By.XPATH, '//button[contains(text(),"Yes")]'
).click()
sleep(1)
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,"is-published")) and not(@draggable="true")]'
)
return draft
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,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,Cloud_server_map.memory_size_xpath), memory_size+'GB'))
webdriverwait(self.Cloud_client_browser,Cloud_server_map.state_pass), '??'))
Cloud_DebugLog.stepinfo(Messages.VM_RESIZE_VERIFY)
def operation(self, text))
Cloud_DebugLog.stepinfo(Messages.VM_operation)
def change_vm_size(self, '??'))
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,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,"(//a[@href='/image/'])[2]")
#flag=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, 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, e:
ACLogger.log_and_print_error(
'_get_link: unable to click on type(%s) text(%s) in UI,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。