Python @H_404[email protected] 模块,@H_404_1@UnexpecteDalertPresentException() 实例源码
我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用selenium.common.exceptions.UnexpecteDalertPresentException()。
def find_xss(self):
print "finding xss..."
current_url = self.driver.current_url
suggestor = XSS_Url_Suggestor(current_url)
urls_to_try = suggestor.get_xss_urls()
print "url is %s"%current_url
print ''
for x in urls_to_try:
try:
self.driver.get(x)
time.sleep(2)
self.driver.get(current_url)
except UnexpecteDalertPresentException:
print "XSS - "+x
pass
except:
print "Some error happened finding xss!"
pass
print ''
print ''
raw_input("Press ENTER to return to menu.")
def click_all_button(self):
""" click the button that redirects to the list of all webcams
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
TimeoutException: it occurs when the element we want is never loaded
"""
try:
# wait until the element is loaded
self.wait.until(lambda driver: driver.find_element_by_id("VERZEICHNIS-button_alle"))
# get the button element and click it
button = self.driver.find_element_by_id("VERZEICHNIS-button_alle")
button.click()
except UnexpecteDalertPresentException:
self.handle_alert()
self.click_all_button()
except:
self.driver.refresh()
self.click_all_button()
def print_city(self):
""" get the city name and put it into the file opened
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
"""
try:
# wait until the element is loaded AND get the city name in the element
self.wait.until(lambda driver: self.driver.find_element_by_class_name("h1"))
city_token = self.driver.find_element_by_class_name("h1").text.split(":")[0]
city = city_token.split()[0]
# write the city name in the file
self.f.write("Switzerland#" + city + "#")
print(city)
except UnexpecteDalertPresentException:
self.handle_alert()
self.print_city()
except:
self.driver.refresh()
self.print_city()
def __wait_for_disappearing(cls):
t = 0
while t < 120:
t = t + 1
try:
elements = env.threadlocal.broWSER.find_elements(cls.by, cls.value)
except NoSuchElementException:
log.step_normal("Element [%s]: NoSuchElementException." % cls.__name__)
elements = []
except BadStatusLine:
log.step_warning("Element [%s]: BadStatusLine." % cls.__name__)
continue
except UnexpecteDalertPresentException:
log.step_warning("Element [%s]: UnexpecteDalertPresentException." % cls.__name__)
if len(elements) == 0:
return True
else:
time.sleep(0.5)
log.step_normal("Element [%s]: WairFordisappearing... Found [%s] Element. Tried [%s] Times." % (cls.__name__, len(elements), t))
return False
def setUp(self):
super(HelloWorldTestBase, self).setUp()
defaultWidth = os.getenv("DEFAULT_WINDOW_WIDTH")
self._followLinkMaxRetries = int(os.getenv('FOLLOW_LINK_MAX_RETRIES', '2'))
try:
if defaultWidth:
# Window must be at least wider than the extra small breakpoint
# to ensure non-mobile devices do not reverting to (small) mobile
# device settings
minWidth = 600
defaultWidth = max(int(defaultWidth), minWidth)
self.log("Set default window with: {0}".format(defaultWidth))
self.windowSetWidth(defaultWidth)
else:
self.log("Maximize window")
self.windowMaximize()
except UnexpecteDalertPresentException as e:
#if self.usesSharedContainer():
# # Can happen when sharing the driver across tests,
# # e.g. when test ended on page the causes a refresh alert
# # This simplifies handling the alert
self.log("Automatically accepting alert: {0}".format(str(e)))
Alert(self.driver).accept()
#else:
# # Should not happen
# raise
self.openBaseUrl()
def open(self, url = None, message = None, handleAlert = True, makeAbsolute = True):
if url is None:
url = "/"
if url.startswith("http"):
prefix = "absolute"
else:
prefix = "relative"
if not url.startswith("/"):
url = "/" + url
if makeAbsolute:
url = self.base_url + url
if message:
message = " " + message
else:
message = ""
self.log("opening {0} URL '{1}'{2}{3}".format(prefix, url, message, \
" (Automatically handle unexpected alerts)" if handleAlert else ""))
try:
self.driver.get(url)
except UnexpecteDalertPresentException:
if handleAlert:
alert = Alert(self.driver)
text = alert.text
if not type(text) is str:
# Likely unicode
text = text.encode('ascii', 'ignore')
self.log("Accepting unexpected alert ({0})".format(text))
alert.accept()
self.log("retrying opening {0}".format(url))
self.open(url, False, makeAbsolute)
else:
raise
self.throttle()
def __repr__(self):
from selenium.common.exceptions import UnexpecteDalertPresentException
try:
return '#<{}:0x{:x} url={!r} title={!r}>'.format(self.__class__.__name__,
self.__hash__() * 2, self.url,
self.title)
except UnexpecteDalertPresentException:
return '#<{}:0x{:x} alert=True>'.format(self.__class__.__name__, self.__hash__() * 2)
except: # noqa
return '#<{}:0x{:x} closed={}>'.format(self.__class__.__name__, self.__hash__() * 2,
self.closed)
def get_tabs(self, tabs):
""" get the list of link addresses of the alphabet tabs that
extract the elements of the tabs of the alphabet which categorize the cameras by alphabet
Returns:
tabs: the list of link addresses of all the alphabet in the tabs
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
TimeoutException: it occurs when the element we want is never loaded
Sometimes tabs returns None type object and I don't kNow why
"""
try:
# wait until the element is loaded
self.wait.until(lambda driver: self.driver.find_element_by_id("VERZEICHNIS-pagination_top"))
# get the tabs' elements
tabs_container = self.driver.find_element_by_id("VERZEICHNIS-pagination_top")
hrefs = tabs_container.find_elements_by_tag_name("a")
# loop through all the tabs to get the href source of them
for href in hrefs:
tabs.append(href.get_attribute("href"))
except UnexpecteDalertPresentException:
self.handle_alert()
self.get_tabs()
except:
self.driver.refresh()
self.get_tabs()
def get_cctvs(self, cctvs):
""" get the list of link addresses of the cameras in the selected alphabet tab
extract the elements of the cameras of the selected alphabet
Returns:
cctvs: the list of link addresses of all the cameras in the selected tab
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
"""
try:
# wait until the element is loaded AND get the cameras' elements
self.wait.until(lambda driver: self.driver.find_elements_by_class_name("thumbnail"))
images = self.driver.find_elements_by_class_name("thumbnail")
# loop throught all the cameras to get the href source of them
for img in images:
cctvs.append(img.get_attribute("href"))
return cctvs
except UnexpecteDalertPresentException:
self.handle_alert()
self.get_cctvs(cctvs)
except:
self.driver.refresh()
self.get_cctvs()
def print_image_src(self):
""" get the camera image url and put it into the file opened
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
TimeoutException: if occurs when the the element is never loaded (the element has different id)
"""
try:
# wait until the element is loaded AND get the image src in the element
self.wait.until(lambda driver: self.driver.find_element_by_id("WEBCAM-bild"))
src = self.driver.find_element_by_id("WEBCAM-bild").get_attribute("src")
# write the image src in the file
self.f.write(src + "#")
print(src)
except UnexpecteDalertPresentException:
self.handle_alert()
self.print_image_src()
except TimeoutException:
link_to_img = self.driver.find_element_by_id("WEBCAM-daylight")
link_to_img.click()
self.wait.until(lambda driver: self.driver.find_element_by_id("WEBCAM_ZOOM-bild"))
src = self.driver.find_element_by_id("WEBCAM_ZOOM-bild").get_attribute("src")
self.f.write(src + "#")
print(src)
self.driver.back()
except:
self.driver.refresh()
self.print_image_src()
def print_geocoord(self):
""" get the location @R_952_4045@ion of the camera and put it into the file opened
when moved to the location webpage,it has the latitude and longitude @R_952_4045@ion in degree/minute/second format
extract it,convert it into the decimal format,and put it into the file
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
"""
try:
# wait until the element is loaded AND get the location @R_952_4045@ion in dms format
self.wait.until(lambda driver: self.driver.find_element_by_xpath("//div[@style='width: 180px; border: 1px solid black; background-color: white; color: black; text-align: center; font: 12px Arial,sans-serif; padding: 1px 3px; z-index: 0; position: absolute; top: 0px; right: 0px;']"))
dms = self.driver.find_element_by_xpath("//div[@style='width: 180px; border: 1px solid black; background-color: white; color: black; text-align: center; font: 12px Arial,sans-serif; padding: 1px 3px; z-index: 0; position: absolute; top: 0px; right: 0px;']").text
# convert the dms format into the decimal format
lat, lon = self.convert_DMS_to_decimal(dms)
# write the latitute and longitude in the file
self.f.write(str(lat) + "#")
self.f.write(str(lon) + "\n")
print(lat, lon)
except UnexpecteDalertPresentException:
self.handle_alert()
self.print_geocoord()
except:
self.driver.refresh()
self.print_geocoord()
def print_geocoord(self):
""" return the location @R_952_4045@ion of the camera
when moved to the location webpage,and return it
Sometimes,the find_element_by_xpath cannot find the element we want.
In that situation,try print_geocoord_help to find it in another way
Return:
lat: latitude of the camera
lon: longitude of the camera
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
TimeoutException: it occurs when the wait.until() can't find the element we want
"""
try:
# wait until the element is loaded AND get the location @R_952_4045@ion in dms format
self.wait.until(lambda driver: self.driver.find_element_by_xpath("//div[@style='width: 180px; border: 1px solid black; background-color: white; color: black; text-align: center; font: 12px Arial,sans-serif; padding: 1px 3px; z-index: 0; position: absolute; top: 0px; right: 0px;']"))
time.sleep(0.5)
dms = self.driver.find_element_by_xpath("//div[@style='width: 180px; border: 1px solid black; background-color: white; color: black; text-align: center; font: 12px Arial, lon = self.convert_DMS_to_decimal(dms)
return lat, lon
except UnexpecteDalertPresentException:
time.sleep(1)
return self.print_geocoord()
except TimeoutException:
self.driver.refresh()
return self.print_geocoord_help()
def print_geocoord_help(self):
""" do the exact same thing as the print_geocoord() does
sometimes,the find_element_by_xpath can't find the element
for this reason,try to find the element in another way
Return:
lat: latitude of the camera
lon: longitude of the camera
Raises:
UnexpecteDalertPresentException: it occurs when a ramdom alert dialog pops up
"""
try:
# wait until the element is loaded AND get the location @R_952_4045@ion in dms format
self.wait.until(lambda driver: self.driver.find_element_by_class_name("gm-style"))
div_container = self.driver.find_element_by_class_name("gm-style")
divs = div_container.find_elements_by_xpath("./div")
dms = divs[7].text
# convert the dms format into the decimal format
lat, lon
except UnexpecteDalertPresentException:
time.sleep(1)
return self.print_geocoord_help()
def __wait(cls):
t = 0
while t < 120:
t = t + 1
try:
elements = env.threadlocal.broWSER.find_elements(cls.by, cls.value)
except NoSuchElementException:
log.step_normal("Element [%s]: NoSuchElementException." % cls.__name__)
elements = []
except BadStatusLine:
log.step_warning("Element [%s]: BadStatusLine." % cls.__name__)
except UnexpecteDalertPresentException:
log.step_warning("Element [%s]: UnexpecteDalertPresentException." % cls.__name__)
if len(elements) == 0:
time.sleep(0.5)
log.step_normal("Element [%s]: Wait 0.5 second,By [%s :: %s :: %s]" % (cls.__name__, cls.by, cls.value, cls.index))
else:
if len(elements) > 1:
log.step_normal("Element [%s]: There are [%s] Elements!" % (cls.__name__, len(elements)))
break
#??????????
if len(elements) < cls.index + 1:
if platform.uname()[0] =='Windows':
log.step_fail("Element [%s]: Element Index Issue! There are [%s] Elements! Index=[%s]" % (cls.__name__, cls.index))
elif platform.uname()[0] =='Linux':
log.step_fail("Element [%s]: Element Index Issue! There are [%s] Elements! Index=[%s]" % (cls.__name__, cls.index))
else:
print '???????'
def __wait_for_appearing(cls):
t = 0
while t < 120:
t = t + 1
try:
elements = env.threadlocal.broWSER.find_elements(cls.by, cls.value)
except NoSuchElementException:
log.step_normal("Element [%s]: NoSuchElementException." % cls.__name__)
elements = []
except BadStatusLine:#????
log.step_warning("Element [%s]: BadStatusLine." % cls.__name__)
continue
except UnexpecteDalertPresentException:
log.step_warning("Element [%s]: UnexpecteDalertPresentException." % cls.__name__)
if len(elements) == 0:
time.sleep(0.5)
log.step_normal("Element [%s]: WaitForAppearing... Wait 1 second,By [%s]" % (cls.__name__, cls.value))
Webbrowser.Refresh(1)
else:
log.step_normal("Element [%s]: Found [%s] Element. Tried [%s] Times." % (cls.__name__, t))
break
def login(self):
if not self.quiet:
print('[*] Logging in as {}'.format(self.account.document))
try:
self.session.get(self.first_page_url)
elem = self.wait.until(EC.visibility_of_element_located((By.NAME, 'txtCPF')))
elem.send_keys(self.account.document)
elem.send_keys(Keys.ENTER)
sleep(3)
self.session.switch_to.frame(self.wait.until(EC.visibility_of_element_located((By.NAME, 'Principal'))))
self.session.switch_to.frame(self.wait.until(EC.visibility_of_element_located((By.NAME, 'MainFrame'))))
if 'iframeContrato' in self.session.page_source:
print('[-] You need to manually accept an usage agreement')
exit(1)
elem = self.wait.until(EC.visibility_of_element_located((By.ID, 'txtSenha')))
elem.send_keys(self.account.password)
elem.send_keys(Keys.ENTER)
self.session.switch_to.default_content()
self.session.switch_to.frame(self.wait.until(EC.visibility_of_element_located((By.NAME, 'Corpo'))))
ola = self.session.find_element_by_id('ola')
soup = bs(ola.get_attribute('innerHTML'))
table = soup.find('table')
self.account.owner = Owner(table.find_all('td')[0].find('strong').text.strip())
self.account.owner.document = self.account.document
self.account.branch = table.find_all('td')[1].text.split()[1]
self.account.number = ''.join(table.find_all('td')[1].text.split()[3].split('.')[:2])
self.account.dac = table.find_all('td')[1].text.split()[3].split('.')[-1]
self.account.print_info()
self.account.owner.print_info()
except UnexpecteDalertPresentException:
print('[-] Login Failed,invalid credentials')
exit(1)
except Exception:
traceback.print_exc()
self.session.save_screenshot('/tmp/screenie.png')
exit(1)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。