本文整理汇总了Python中splinter.Browser.evaluate_script方法的典型用法代码示例。如果您正苦于以下问题:Python Browser.evaluate_script方法的具体用法?Python Browser.evaluate_script怎么用?Python Browser.evaluate_script使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类splinter.Browser
的用法示例。
在下文中一共展示了Browser.evaluate_script方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getPrivNoteURL
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
def getPrivNoteURL(message):
browser = Browser('phantomjs')
#ghost.show()
browser.visit("https://privnote.com/")
command = "document.getElementById('id_body').value='"+message+"';"
result = browser.evaluate_script(command)
command = "document.getElementById('button').click();"
result = browser.evaluate_script(command)
time.sleep(2)
command = "document.getElementById('notelink').value;"
result = browser.evaluate_script(command)
print (result)
示例2: submitQueue
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
def submitQueue(NETID, PASSWORD, SECURITY_QUESTIONS):
browser = Browser()
# netid page
browser.visit("https://puaccess.princeton.edu/psp/hsprod/EMPLOYEE/HRMS/h/?tab=DEFAULT")
browser.fill('userid', NETID)
browser.find_by_value("Continue").first.click()
# password page
browser.fill('Bharosa_Password_PadDataField', PASSWORD)
browser.evaluate_script("Bharosa_Password_Pad.keyPress('ENTERKEY');")
# security question page
html = browser.html
for key in SECURITY_QUESTIONS.keys():
if key in html:
answer = SECURITY_QUESTIONS[key]
browser.fill('Bharosa_Challenge_PadDataField', answer)
browser.evaluate_script("Bharosa_Challenge_Pad.keyPress('ENTERKEY');")
time.sleep(2)
# welcome to SCORE
browser.find_link_by_text("Student Center").first.click()
# student center, start by busting out of the iframe
browser.visit("https://puaccess.princeton.edu/psc/hsprod/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL?PORTALPARAM_PTCNAV=HC_SSS_STUDENT_CENTER&EOPP.SCNode=HRMS&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=ADMN_SCORE&EOPP.SCLabel=&EOPP.SCPTcname=ADMN_SC_SP_SCORE&FolderPath=PORTAL_ROOT_OBJECT.PORTAL_BASE_DATA.CO_NAVIGATION_COLLECTIONS.ADMN_SCORE.ADMN_S200801281459482840968047&IsFolder=false&PortalActualURL=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL&PortalContentURL=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL&PortalContentProvider=HRMS&PortalCRefLabel=Student%20Center&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fpuaccess.princeton.edu%2fpsp%2fhsprod%2f&PortalURI=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2f&PortalHostNode=HRMS&NoCrumbs=yes&PortalKeyStruct=yes")
browser.select('DERIVED_SSS_SCL_SSS_MORE_ACADEMICS', "1005")
browser.find_by_id("DERIVED_SSS_SCL_SSS_GO_1").first.click()
# pick semester
browser.choose("SSR_DUMMY_RECV1$sels$0", "1")
browser.find_by_id("DERIVED_SSS_SCT_SSR_PB_GO").first.click()
# select classes to add... class should already be in queue
browser.find_by_id("DERIVED_REGFRM1_LINK_ADD_ENRL$115$").first.click()
# confirm classes
browser.find_by_id("DERIVED_REGFRM1_SSR_PB_SUBMIT").first.click()
示例3: SplinterBrowserDriver
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
#.........这里部分代码省略.........
@property
def page_source(self):
return self._browser.html
@property
def page_title(self):
return self._browser.title
def open_url(self, url):
self._browser.driver.get(url)
def quit(self):
return self._browser.quit()
def is_element_visible(self, element):
return element.visible
def get_element_text(self, element):
return element.text
def get_element_by_xpath(self, selector):
return self._browser.find_by_xpath(selector)
def get_element_by_css(self, selector):
return self._browser.find_by_css(selector)
def get_element_by_id(self, selector):
return self._browser.find_by_id(selector)
def get_element_by_tag(self, selector):
return self._browser.find_by_tag(selector)
@element_action
def type(self, element, text, slowly=False):
return element.type(text, slowly)
@element_action
def fill(self, element, text):
return element.fill(text)
@element_action
def clear(self, element):
self.fill(element, '')
@element_action
def click(self, element):
return element.click()
@element_action
def check(self, element):
return element.check()
@element_action
def uncheck(self, element):
return element.uncheck()
@element_action
def mouse_over(self, element):
return element.mouse_over()
@element_action
def mouse_out(self, element):
return element.mouse_out()
def reload(self):
return self._browser.reload()
def go_back(self):
return self._browser.back()
def go_forward(self):
return self._browser.forward()
def execute_script(self, script):
return self._browser.evaluate_script(script)
def get_iframe(self, iframe_id):
return self._browser.get_iframe(iframe_id)
def get_alert(self):
return self._browser.get_alert()
def attach_file(self, input_name, file_path):
return self._browser.attach_file(input_name, file_path)
def wait_pageload(self, timeout=30):
wait_interval = 0.05
elapsed = 0
while self.execute_script('document.readyState') != 'complete':
self.wait(wait_interval)
elapsed += wait_interval
if elapsed > timeout:
raise PageNotLoadedException
def click_and_wait(self, element, timeout=30):
self.click(element)
self.wait_pageload(timeout)
示例4: range
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
for provider in ['us-east-1', 'us-west-2', 'us-west-1', 'eu-west-1', 'ap-southeast-1', 'ap-northeast-1', 'ap-southeast-2','sa-east-1']:
browser.visit('https://console.aws.amazon.com/ec2/v2/home?region=%s' % provider)
time.sleep(6)
#wait to load otherwise it fails
browser.find_by_css('.gwt-Button').click()
time.sleep(6)
browser.find_by_css('#scenario').click()
browser.find_by_name('key-pair-method')[2].click()
#select no key, because for example ap-southeast-2 does not have the existing keys,
#and this asks for a key without letting you to proceed with the images
provider_images = []
for i in range (1, len(browser.find_by_css('tr.scenario_description'))):
# Check if next image is windows (to ignore it)
if 'Windows' in browser.evaluate_script("$('tr.scenario_description').eq(%d).text()" % i):
continue
# Click image list item
browser.execute_script("$('tr.scenario_description').eq(%d).click()" % i)
# If 64-bit is available
if not browser.evaluate_script("$('tr.scenario_description').eq(%d).find('input#x86_64').attr('disabled')" % i):
# Click 64-bit radio button
browser.execute_script("$('tr.scenario_description').eq(%d).find('input#x86_64').click()" % i)
# Click continue
browser.execute_script("$('#qs_continue_scenario .elasticbig-container').click()")
# Get image ami
line = browser.evaluate_script("$('.wizard_review h1.ami_name').eq(0).text()")
ami = 'ami' + line.split(' (ami')[1].replace(')','')
title = line.split(' (ami')[0] + ' 64bit'
示例5: DataNodeTestCase
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
#.........这里部分代码省略.........
create_data(self)
original_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[1].value
# Clone the node
self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td/a[@class='edit']").first.click()
self.browser.find_by_name('Name').first.fill(original_name + " clone")
self.browser.find_by_name("as-new").first.click()
# Check that two nodes exist
original_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[1].value
clone_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[4].value
spin_assert(lambda: self.assertEqual(original_name, "Bob's node"))
spin_assert(lambda: self.assertEqual(clone_name, "Bob's node clone"))
Graph.objects.get(name="Bob's graph").destroy()
def test_sigma_visualization_in_node_view(self):
create_graph(self)
create_schema(self)
create_type(self)
# Adding relationship to the type
self.browser.find_by_id('allowedRelations').first.click()
self.browser.select('source', '1')
self.browser.find_by_name('name').fill("Bob's rel")
self.browser.select('target', '1')
self.browser.find_by_id('id_description').fill(
'The loved relationship')
self.browser.find_by_value('Save Type').first.click()
text = self.browser.find_by_xpath(
"//div[@class='form-row indent']/label").first.value
spin_assert(lambda: self.assertNotEqual(text.find("Bob's rel"), -1))
# Creating nodes
create_node(self, 'Bob')
create_node(self, 'Alice')
# Creating relationship between nodes
self.browser.find_by_id('dataMenu').first.click()
self.browser.find_by_xpath("//td[@class='dataActions']/a[@class='dataOption list']").first.click()
self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click()
self.browser.find_by_xpath("//li[@class='token-input-input-token']/input").first.fill('Alice')
self.browser.is_element_present_by_id("id_user_wait", wait_time=5)
self.browser.find_by_xpath("//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b").first.click()
self.browser.find_by_value("Save Bob's type").first.click()
# Checking
self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td/a[@title='View node']/p[text()='Alice']").first.click()
self.browser.is_element_present_by_id('wait_for_js', 3)
js_code = '''
var instance = sigma.instances(0);
sylva.test_node_count = instance.graph.nodes().length;
'''
self.browser.execute_script(js_code)
text = self.browser.evaluate_script('sylva.test_node_count')
spin_assert(lambda: self.assertEqual(text, 2))
Graph.objects.get(name="Bob's graph").destroy()
def test_graph_export_gexf(self):
create_graph(self)
create_schema(self)
create_type(self)
create_data(self)
self.browser.find_by_id('toolsMenu').first.click()
cookies = {self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"]}
result = requests.get(self.live_server_url + '/tools/bobs-graph/export/gexf/', cookies=cookies)
spin_assert(lambda: self.assertEqual(
result.headers['content-type'], 'application/xml'))
spin_assert(lambda: self.assertEqual(
self.browser.status_code.is_success(), True))
fw = open('sylva/sylva/tests/files/bobs-graph.gexf', 'w')
fw.write(result.content)
fw.close()
f = open('sylva/sylva/tests/files/bobs-graph.gexf')
xmlFile = ""
for line in f:
xmlFile += line
f.close()
spin_assert(lambda: self.assertEqual(xmlFile, result.content))
Graph.objects.get(name="Bob's graph").destroy()
def test_graph_export_csv(self):
create_graph(self)
create_schema(self)
create_type(self)
create_data(self)
self.browser.find_by_id('toolsMenu').first.click()
cookies = {self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"]}
result = requests.get(self.live_server_url + '/tools/bobs-graph/export/csv/', cookies=cookies)
spin_assert(lambda: self.assertEqual(
result.headers['content-type'], 'application/zip'))
spin_assert(lambda: self.assertEqual(
self.browser.status_code.is_success(), True))
test_file = StringIO(result.content)
csv_zip = ZipFile(test_file)
for name in csv_zip.namelist():
fw = open('sylva/sylva/tests/files/' + name, 'w')
fw.write(csv_zip.read(name))
fw.close()
for name in csv_zip.namelist():
f = open('sylva/sylva/tests/files/' + name)
csvFile = ""
for line in f:
csvFile += line
f.close()
spin_assert(lambda: self.assertEqual(csv_zip.read(name), csvFile))
Graph.objects.get(name="Bob's graph").destroy()
示例6: HomePageWebTests
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
class HomePageWebTests(StaticLiveServerTestCase):
def setUp(self):
self.user1 = UserFactory.build()
self.user1.set_password('abc')
self.user1.save()
self.browser = Browser()
def tearDown(self):
self.browser.quit()
def login_helper(self, username, password):
self.browser.visit('%s%s' % (self.live_server_url, '/accounts/login/'))
self.browser.fill('username', username)
self.browser.fill('password', password)
self.browser.find_by_value('Log in').first.click()
# Test 2
# Check for login link from anonymous get of homepage
def test_anon_login(self):
self.browser.visit('%s%s' % (self.live_server_url, '/'))
login_link = self.browser.find_by_tag('a')[2]
self.assertEqual(
'%s%s' % (self.live_server_url, '/accounts/login/'),
login_link['href']
)
# Test 3
# Check for register link from anonymous get of homepage
def test_anon_register(self):
self.browser.visit('%s%s' % (self.live_server_url, '/'))
register_link = self.browser.find_by_tag('a')[3]
self.assertEqual(
'%s%s' % (self.live_server_url, '/accounts/register/'),
register_link['href']
)
# Test 4
# Check for user login success
def test_login_success(self):
self.login_helper(self.user1.username, 'abc')
self.assertEqual(
self.browser.url,
'%s%s' % (self.live_server_url, '/profile/')
)
logout_link = self.browser.find_by_tag('a')[6]
self.assertEqual(
'%s%s' % (self.live_server_url, '/accounts/logout/?next=/'),
logout_link['href']
)
greeting = self.browser.find_by_tag('h1')[0]
self.assertEqual(
'%s%s%s' % ('Well howdy there, ', self.user1.username, '!'),
greeting.text
)
# Test 5
# Check for user logout success
def test_logout_success(self):
self.login_helper(self.user1.username, 'abc')
self.browser.find_by_tag('a')[6].click()
self.assertEqual(
self.browser.url,
'%s%s' % (self.live_server_url, '/')
)
# Test 6
# Register brand new user
def test_registration(self):
self.browser.visit(
'%s%s' % (self.live_server_url, '/accounts/register/')
)
self.browser.fill('username', 'joseph')
self.browser.fill('email', '[email protected]')
self.browser.fill('password1', '123')
self.browser.fill('password2', '123')
self.browser.find_by_value('Submit').first.click()
self.assertEqual(
self.browser.url,
'%s%s' % (self.live_server_url, '/accounts/register/complete/')
)
link_end = mail.outbox[0].body.split('days:')[1].split()[0][18:]
link = '%s%s' % (self.live_server_url, link_end)
self.browser.evaluate_script('document.location="%s"' % link)
self.assertEqual(
self.browser.url,
'%s%s' % (self.live_server_url, '/accounts/activate/complete/')
)
self.login_helper('joseph', '123')
greeting = self.browser.find_by_tag('h1')[0]
self.assertEqual('Well howdy there, joseph!', greeting.text)
示例7: range
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
except:
print "Failed on %s" % username
continue
# get rid of the login overlay
try:
browser.find_by_css(".cancel").first.click()
time.sleep(1)
except:
pass
# scroll to bottom several times
for i in range(5):
browser.evaluate_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
for element in browser.find_by_css(".inline_editor_value"):
try:
text = element.find_by_css("div").first.find_by_css("div").first.text
text_ascii = text.encode('ascii', 'replace')
posts.append((username,text_ascii))
except:
pass
with open("output.csv", "a") as f:
csv_out = csv.writer(f)
csv_out.writerows(posts)
示例8: angular_app_loaded
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
def angular_app_loaded(browser: Browser) -> bool:
"""Check that the angular app is loaded."""
code = 'window.hasOwnProperty("adhocracy") '\
'&& window.adhocracy.hasOwnProperty("loadState") '\
'&& window.adhocracy.loadState === "complete";'
return browser.evaluate_script(code)
示例9: DashboardTestCase
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
class DashboardTestCase(LiveServerTestCase):
"""
These tests check basic functions of Sylva's dashboard.
"""
def setUp(self):
self.browser = Browser()
socket.setdefaulttimeout(30)
signup(self, "bob", "[email protected]", "bob_secret")
def tearDown(self):
logout(self)
self.browser.quit()
@classmethod
def tearDownClass(cls):
sleep(10) # It needs some time for close the LiverServerTestCase
super(DashboardTestCase, cls).tearDownClass()
def test_dashboard(self):
signin(self, "bob", "bob_secret")
spin_assert(lambda: self.assertEquals(self.browser.title, "SylvaDB - Dashboard"))
text = self.browser.find_by_xpath("//header[@class='global']/h1").first.value
spin_assert(lambda: self.assertEqual(text, "Dashboard"))
def test_dashboard_new_graph(self):
signin(self, "bob", "bob_secret")
create_graph(self)
Graph.objects.get(name="Bob's graph").destroy()
def test_dashboard_graph_preview(self):
"""
This test, after create a graph with data, checks the Sigma
visualization running a simple JavaScript code. This code gets the
current instance of Sigma and checks the data with Sylva JavaScript
object.
"""
signin(self, "bob", "bob_secret")
create_graph(self)
create_schema(self)
create_type(self)
create_data(self)
self.browser.find_link_by_href("/graphs/bobs-graph/").first.click()
self.browser.is_element_present_by_id("wait_for_js", 3)
js_code = """
var instance = sigma.instances(0);
var node = instance.graph.nodes()[0];
sylva.test_node_name = node.properties.Name;
"""
self.browser.execute_script(js_code)
text = self.browser.evaluate_script("sylva.test_node_name")
Graph.objects.get(name="Bob's graph").destroy()
spin_assert(lambda: self.assertNotEqual(text.find("Bob's node"), -1))
def test_automatic_tour(self):
"""
Thist test checks that the tour starts automatically after signup, only
once.
"""
self.browser.is_element_present_by_id("wait_for_cookie_tour", 3)
signin(self, "bob", "bob_secret")
exist = self.browser.is_element_present_by_xpath("//div[@class='joyride-content-wrapper']")
spin_assert(lambda: self.assertEqual(exist, True))
self.browser.visit(self.live_server_url + "/dashboard/")
exist = self.browser.is_element_present_by_xpath("//div[@class='joyride-content-wrapper']")
spin_assert(lambda: self.assertNotEqual(exist, True))
示例10: __init__
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
class HackFreeRice:
def __init__(self, browserType='chrome'):
self.correct = 0
self.incorrect = 0
self.readCredentials()
# Initialize splinter (other possible values include 'phantomjs' and 'firefox')
self.browser = Browser(browserType)
def initialize(self, verbose=False):
# Initialize until it is successful
while True:
if self.tryInitialize():
if verbose:
print 'Successfully initialized.'
break
def readCredentials(self, verbose=False):
# Read credentials from file
with open('config') as f:
username, password = f.readlines()
self.username = username.strip()
self.password = password.strip()
if verbose:
print 'Your username is %s' % self.username
print 'Your password is %s' % self.password
def tryInitialize(self, verbose=False):
# Open freerice
self.browser.visit('http://freerice.com/user/login')
# Close pop-up, if present
if self.browser.is_element_present_by_id('wfp-ew-dialog-close'):
if self.browser.find_by_id('wfp-ew-dialog-close').first.visible:
# Closed popup if present and visible
self.browser.find_by_id('wfp-ew-dialog-close').click()
# Login
self.browser.execute_script("$('#edit-name').val('%s')" % self.username)
self.browser.execute_script("$('#edit-pass').val('%s')" % self.password)
self.browser.execute_script("$('#edit-submit').click()")
already_logged_in = self.browser.is_text_present('Logout')
login_check_string = '%s has earned' % self.username
successful_login = self.browser.is_text_present(login_check_string)
if already_logged_in or successful_login:
if verbose:
print 'Successfully logged in!'
else:
if verbose:
print 'Login failed.'
return False
# Change subject to math
self.browser.execute_script("window.location.href = 'http://freerice.com/frapi/category_selected/18492'")
if self.browser.is_text_present('Multiplication Table'):
if verbose:
print 'Successfully navigated to Multiplication Table'
return True
else:
return False
def doQuestion(self, verbose=False):
# Close twitter solicitation, if present
self.browser.execute_script("$('#twt-skip').click()")
question_text = self.browser.evaluate_script("$('#question-title').text()")
question_text = question_text.split('loader')
question_text = ''.join(question_text)
if verbose:
print 'The question is: %s' % question_text
question_text = string.replace(question_text, ' x ', '*').strip()
if verbose:
print 'The code representation of the question is: %s' % question_text
question_answer = self.browser.evaluate_script(question_text)
if verbose:
print 'The answer is: %s' % question_answer
add_id_script = "$('a:contains(\"%s\").answer-item').attr('id', 'clickthisone')" % question_answer
if verbose:
print 'Script to add id is:', add_id_script
self.browser.execute_script(add_id_script)
self.browser.find_by_id('clickthisone').click()
if self.browser.is_text_present('Correct!'):
print 'Got the answer right. Yeah!'
self.correct += 1
else:
print 'Oops. Got that one wrong.'
self.incorrect += 1
print 'You have donated %s grains of rice!' % str(10 * self.correct)
示例11: Browser
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import evaluate_script [as 别名]
from splinter import Browser
url = "http://www.premierinn.com"
browser = Browser('phantomjs')
browser.visit(url)
html = browser.evaluate_script("document.documentElement.outerHTML")
f = open('testhtml.txt', 'w')
f.write(html)
f.close