本文整理汇总了Python中splinter.Browser.execute_script方法的典型用法代码示例。如果您正苦于以下问题:Python Browser.execute_script方法的具体用法?Python Browser.execute_script怎么用?Python Browser.execute_script使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类splinter.Browser
的用法示例。
在下文中一共展示了Browser.execute_script方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_0_http_browser_download
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
def test_0_http_browser_download(self):
path = self.get_endpoint_path("HTTPServer")
url = "http://{0}/thredds/fileServer/{1}".format(self.data_node, path)
OpenID = "https://{0}/esgf-idp/openid/{1}".format(self.idp_node, self.username)
pf = {"browser.helperApps.neverAsk.saveToDisk": "application/x-netcdf, application/netcdf"}
browser = Browser("firefox", profile_preferences=pf)
browser.visit(url)
if browser.status_code.is_success() is True:
browser.quit()
return
browser.find_by_css("input.custom-combobox-input").fill(OpenID)
browser.find_by_value("GO").click()
browser.find_by_id("password").fill(self.password)
browser.find_by_value("SUBMIT").click()
# To Do only if user is not enrolled in a group
if browser.is_text_present("Group Registration Request"):
# Chosing First Registration Group
browser.find_by_id("button_1").click()
# Accepting License Agreement
browser.execute_script("myForm.submit();")
# Clicking on 'Download data button'
browser.find_by_id("goButton").click()
browser.quit()
示例2: test_0_http_browser_download
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
def test_0_http_browser_download(self):
path = self.get_endpoint_path('HTTPServer')
url = "http://{0}/thredds/fileServer/{1}".format(self.data_node, path)
OpenID = "https://{0}/esgf-idp/openid/{1}".format(self.idp_node, self.username)
pf={'browser.helperApps.neverAsk.saveToDisk':'application/x-netcdf, application/netcdf'}
browser = Browser('firefox', profile_preferences=pf)
browser.visit(url)
if browser.status_code.is_success() is True:
browser.quit()
return
browser.find_by_id('openid_identifier').fill(OpenID)
browser.find_by_value('GO').click()
browser.find_by_id('password').fill(self.password)
browser.find_by_value('SUBMIT').click()
# To Do only if user is not enrolled in a group
if browser.is_text_present('Group Registration Request'):
# Chosing First Registration Group
browser.find_by_id('button_1').click()
# Accepting License Agreement
browser.execute_script('myForm.submit();')
# Clicking on 'Download data button'
browser.find_by_id('goButton').click()
browser.quit()
示例3: PinterestCrawler
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
class PinterestCrawler(object):
def __init__(self, url):
self.navigator = Browser()
self.url = url
def login_to_pinterest(self, login, password):
email_input = login
password_input = password
emaillogin = self.navigator.find_by_css(
'body > div > div.appContent > div.mainContainer > div > div > div > form > ul > li.loginUsername > input')[0]
emailpassword = self.navigator.find_by_css('body > div > div.appContent > div.mainContainer > div > div > div > form > ul > li.loginPassword > input')[0]
loginbutton = self.navigator.find_by_css('body > div > div.appContent > div.mainContainer > div > div > div > form > div.formFooter > div > button')[0]
emaillogin.fill(email_input)
emailpassword.fill(password_input)
time.sleep(random.randint(2, 6))
return loginbutton.click()
def clickfollow(self, url):
self.navigator.visit(url)
time.sleep(6)
self.navigator.execute_script(
'window.scrollTo(50,document.body.scrollHeight);')
css_path = 'body > div.App.AppBase.Module.full > div.appContent > div.mainContainer > div.Module.UserProfilePage > div.Module.UserProfileContent > div > div > div:nth-child({0}) > div > button'
new_child = 1
while new_child <= 50:
css_path2 = css_path.format(new_child)
time.sleep(2)
self.navigator.find_by_css(css_path2)[0].click()
new_child += 1
time.sleep(random.randint(3, 12))
def main(self):
self.navigator.visit(self.url)
self.login_to_pinterest('[email protected]', 'blackhouse123')
self.clickfollow('https://www.pinterest.com/PaleoLivingMag/followers/')
示例4: DataNodeTestCase
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
class DataNodeTestCase(LiveServerTestCase):
"""
A set of tests to test all interaction related to the creation and
deletion of nodes and relationships. Also, we test export the data in two
formats: gexf and csv.
"""
def setUp(self):
self.browser = Browser()
socket.setdefaulttimeout(30)
signup(self, 'bob', '[email protected]', 'bob_secret')
signin(self, 'bob', '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(DataNodeTestCase, cls).tearDownClass()
def test_data_node_addition(self):
create_graph(self)
create_schema(self)
create_type(self)
create_data(self)
# Check the node name
self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click()
text = self.browser.find_by_id('propertiesTitle').first.value
spin_assert(lambda: self.assertEqual(text, 'Properties'))
self.browser.find_by_xpath("//span[@class='buttonLinkOption buttonLinkRight']/a").first.click()
self.browser.choose('confirm', '1')
self.browser.find_by_value('Continue').first.click()
text = self.browser.find_by_xpath("//div[@class='indent']/div").first.value
Graph.objects.get(name="Bob's graph").destroy()
spin_assert(lambda: self.assertEqual(text, 'Nodes: 0'))
def test_data_node_addition_rel_add_del(self):
create_graph(self)
create_schema(self)
create_type(self)
create_node(self, "Bob")
create_node(self, "Alice")
# We create a allowed relation
js_code = "$('a#schema-link')[0].click();"
self.browser.execute_script(js_code)
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("This the allowed relationship for Bob's graph")
self.browser.find_by_value('Save Type').first.click()
spin_assert(lambda: self.assertEqual(
self.browser.title, "SylvaDB - Bob's graph"))
# We create the link between the 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", 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()
# Delete the relationship
self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click()
self.browser.find_by_xpath("//span[@class='all-relationships incoming-relationships i_bobs_rel1-relationships']//a[@class='delete-row initial-form floating']").first.click()
self.browser.find_by_value("Save Bob's type").first.click()
self.browser.find_link_by_href('/graphs/bobs-graph/').first.click()
text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value
spin_assert(lambda: self.assertEqual(text, "0 relationships"))
Graph.objects.get(name="Bob's graph").destroy()
def test_node_type_deletion_keeping_nodes(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()
self.browser.find_link_by_href('/graphs/bobs-graph/').first.click()
text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value
#.........这里部分代码省略.........
示例5: line_login
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
def line_login(browser, user_name, password, code):
"""
lineに自動ログインして、パラメータのカードコードを入力し、チャージする。
チャージした結果を返す。
:param browser:ブラウザインスタンス
:param user_name:ログインユーザネーム
:param password:ログインパスワード
:param code:ギフトカードコード
:return:チャージ結果
"""
# ログインページを開く
browser = Browser('firefox')
url = 'https://store.line.me/home/'
browser.visit(url)
# ログインする
login_submit = browser.find_link_by_partial_href('login')
if login_submit:
login_submit.click()
else:
html_code = browser.html
return {
'code': 4,
'message': "サイト上に問題が発生しました。(サイトがアクセスできない、またはネットが遅すぎる可能性があります。)",
'htmlcode': html_code
}
username_input_field = browser.find_by_id('id')
password_input_field = browser.find_by_id('passwd')
login_submit = browser.find_by_value('Login')
if username_input_field and password_input_field and login_submit:
username_input_field.fill(user_name)
password_input_field.fill(password)
login_submit.click()
else:
html_code = browser.html
return {
'code': 4,
'message': "サイト上に問題が発生しました。(サイトがアクセスできない、またはネットが遅すぎる可能性があります。)",
'htmlcode': html_code
}
# ログイン画像認識があるかどうかチェックする
#captcha_image_field = browser.find_by_css('img.FnCaptchaImg')
#メールアドレスまたパスワードをチェックする
login_alert_field = browser.find_by_css('p.mdMN02Txt')
if browser.is_element_present_by_css('p.mdMN02Txt'):
result = login_alert_field.value
if result.find(unicode('The password you have entered is invalid, or you have not registered your email address with LINE.')) != -1:
html_code = browser.html
return {
'code': 2,
'message': 'メールアドレスまたはパスワードが正しくありません。',
'htmlcode': html_code
}
# チャージ画面に移動する
browser.find_by_text('Charge').click()
browser.windows.current = browser.windows[1]
browser.find_by_id('70002').click()
browser.execute_script("charge(this); return false;")
# チャージする
code_input_field = browser.find_by_id('FnSerialNumber')
code_input_field.fill(code)
time.sleep(9000)
browser.execute_script("javascript:doCharge(this);return false;")
result = browser.find_by_css('p.mdLYR11Txt01').value
browser.quit()
return result
示例6: GPlusEventManager
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
class GPlusEventManager(object):
def __init__(self, email, passwd, otp):
self.email = email
self.passwd = passwd
self.br = Browser('firefox')
atexit.register(self.force_br_quit)
# To dynamically load jQuery into the HTML head
self.loadjq = """var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src =
'//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
head.appendChild(script);"""
self.otp = otp
self.logged_in = self.login()
def force_br_quit(self):
try:
self.br.quit()
except:
pass
def create(self, title, desc, date, time):
""" Create a new Google Plus event """
if not self.logged_in:
self.logged_in = self.login()
create_btn = 'div[guidedhelpid="events_create_event_button"]'
self.br.find_by_css(create_btn)[0].click()
return self.complete_form(title, desc, date, time, update=False)
def update(self, id, title=None, desc=None, date=None, time=None):
""" Update a Google Plus event """
if not self.logged_in:
self.logged_in = self.login()
self.br.visit(id)
dropdown = 'div[class="A7kfHd q3sPdd"]'
while self.br.is_element_not_present_by_css(dropdown):
pass
self.br.find_by_css(dropdown).click()
self.br.find_by_xpath('//*[@id=":o"]/div').click()
return self.complete_form(title, desc, date, time, update=True)
def complete_form(self, title, desc, date, time, update):
'''Fill event create/edit form,
the CSS selectors are valid in both types of form'''
title_input = 'input[placeholder="Event title"]'
while self.br.is_element_not_present_by_css(title_input):
pass
if title:
title_placeholder = self.br.find_by_css(title_input)
title_placeholder.fill(title)
if date:
self.br.find_by_css('input[class="g-A-G T4 lUa"]').click()
rm_date = '''document.body.getElementsByClassName("g-A-G T4 lUa")
[0].value = ""'''
self.br.execute_script(rm_date)
date_field = 'input[class="g-A-G T4 lUa"]'
self.br.find_by_css(date_field).type('{}\t'.format(date))
if time:
self.br.execute_script(self.loadjq)
loaded = False
rm_time = '$(".EKa")[0].value = ""'
while not loaded:
try:
self.br.execute_script(rm_time)
except Exception, e:
pass
else:
loaded = True
time_field = 'input[class="g-A-G T4 EKa"]'
self.br.find_by_css(time_field)[0].type('{}'.format(time))
if desc:
set_desc = '''document.body.getElementsByClassName("yd editable")
[1].innerHTML = "{}"'''.format(desc)
self.br.execute_script(set_desc)
invite_btn = self.br.find_by_css('div[guidedhelpid="sharebutton"]')
invite_inp = self.br.find_by_css('input[class="i-j-h-G-G"]')
invite_btn.click()
if not update: # If new entry, invite Public group by default
invite_inp.click()
invite_inp.type('Public\n')
invite_btn.click()
while not self.br.is_text_present('Going ('):
pass # wait on page load for new event
url = self.br.url
self.br.quit()
return url # return event url
示例7: ToolsTestCaseCsv
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
class ToolsTestCaseCsv(LiveServerTestCase):
"""
A master test to check the behaviour of the new 'auto' fields.
Actually only works with gephi format.
"""
def setUp(self):
self.browser = Browser()
socket.setdefaulttimeout(30)
signup(self, 'bob', '[email protected]', 'bob_secret')
signin(self, 'bob', 'bob_secret')
self.firstGraphName = "bobgraph"
self.secondGraphName = "alicegraph"
def tearDown(self):
logout(self)
self.browser.quit()
@classmethod
def tearDownClass(cls):
sleep(10) # It needs some time for close the LiverServerTestCase
super(ToolsTestCaseCsv, cls).tearDownClass()
def test_graph_export_csv(self):
# Create a graph with a auto_user property
create_graph(self, self.firstGraphName)
create_advanced_schema(self, self.firstGraphName)
create_advanced_type(self, self.firstGraphName, "e")
create_advanced_data(self)
# Create new graph for import the data
import_advanced_schema_csv(self, self.firstGraphName, self.secondGraphName)
# Data import
self.browser.find_by_id('toolsMenu').first.click()
self.browser.find_link_by_href('/tools/' + self.secondGraphName + '/import/').first.click()
self.browser.find_by_id('csv-radio').first.click()
# Change the display field of input to attach the file
script = """
$('#files').css('display', '');
"""
self.browser.execute_script(script)
self.browser.is_text_present('Drop your nodes files here', wait_time=10)
# Import the nodes
file_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'files/csv/bobs-type.csv'
)
self.browser.attach_file('file', file_path)
self.browser.is_text_present('Nodes files loaded. Loading edges files...', wait_time=10)
# Wait until the data is imported
self.browser.is_text_present('Now drop your edges files', wait_time=10)
# Change the display field of input to attach the file
script = """
$('#files2').css('display', '');
"""
self.browser.execute_script(script)
# Import the relationships
file_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'files/csv/bobs-rels.csv'
)
self.browser.attach_file('file2', file_path)
self.browser.is_text_present('Data loaded. Uploading to the server...', wait_time=10)
# Wait until the data is imported
self.browser.is_text_present('Data uploaded.', wait_time=10)
# Check that nodes and relationships are ok
self.browser.find_by_id('dataMenu').first.click()
self.browser.find_by_xpath("//a[@class='dataOption list']").first.click()
alicegraph = Graph.objects.get(name=self.secondGraphName)
alicegraphNodes = alicegraph.nodes.count()
spin_assert(lambda: self.assertEqual(3, alicegraph.nodes.count()))
spin_assert(lambda: self.assertEqual(
1, alicegraph.relationships.count()))
# Add new nodes and relationships and check all is correct
self.browser.find_by_id('dataMenu').first.click()
self.browser.find_by_xpath(
"//a[@class='dataOption new']").first.click()
text = self.browser.find_by_id('propertiesTitle').first.value
spin_assert(lambda: self.assertEqual(text, 'Properties'))
self.browser.find_by_value("Save Bob's type").first.click()
text = self.browser.find_by_xpath("//div[@class='pagination']/span[@class='pagination-info']").first.value
spin_assert(lambda: self.assertNotEqual(
text.find(" elements Bob's type."), -1))
spin_assert(lambda: self.assertEqual(
alicegraphNodes + 1, alicegraph.nodes.count()))
# Destroy the databases
Graph.objects.get(name=self.firstGraphName).destroy()
Graph.objects.get(name=self.secondGraphName).destroy()
示例8: __init__
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
#.........这里部分代码省略.........
return personal_learning_plans, personal_learning_plans, mandatory_learning
def member_permits(self, member_number, member_name):
self.lookup_member(member_number)
# Select Permits
self.wait_then_click_xpath('//*[@id="LBTN4"]')
permits = self.fetch_table('tbl_p4_permits')
if permits is not None:
permits['member'] = member_number
permits['name'] = member_name
return permits
@lru_cache()
def get_all_adult_trainers(self):
self.adult_training()
return self.fetch_table('tbl_p1_results')
@lru_cache()
def get_all_group_members(self):
self.search()
self._browser.is_element_present_by_xpath('//*[@id = "MemberSearch"]/tbody', wait_time=10)
time.sleep(1)
# Hack to ensure that all of the search results loaded.
for i in range(0, 5):
self._browser.execute_script(
'document.getElementById("ctl00_main_working_panel_scrollarea").scrollTop = 100000')
time.sleep(1)
return self.fetch_table('MemberSearch')
def export(self, section):
# Select the My Scouting link.
self._browser.is_text_present('My Scouting', wait_time=30)
self._browser.click_link_by_text('My Scouting')
# Click the "Group Sections" hotspot.
self.wait_then_click_xpath('//*[@id="TR_HIER7"]/h2')
# Clink the link that shows the number of members in the section.
# This is the one bit that is section specific.
# We might be able to match on the Section name in the list,
# which would make it more robust but at present we just hard
# the location in the list.
section_map = {
'garrick': 2,
'paget': 3,
'swinfen': 4,
'brown': 4,
'maclean': 5,
'rowallan': 6,
'somers': 7,
'boswell': 8,
'erasmus': 9,
'johnson': 10
}
self.wait_then_click_xpath(
'//*[@id="TR_HIER7_TBL"]/tbody/tr[{}]/td[4]/a'.format(
示例9: range
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
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'
# Save ami
new_pair = (ami, title)
if new_pair not in provider_images:
provider_images.append(new_pair)
示例10: Browser
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
from splinter import Browser
browser = Browser('chrome')
#connect to database
import pymongo
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.Singapore_TCM_Database
tcm_detail = db['tcm_detail']
tcm_certs = db['tcm_certs']
tcm_work = db['tcm_work']
browser.visit('https://prs.moh.gov.sg/prs/internet/profSearch/showSearchSummaryByName.action?hpe=TCM')
browser.execute_script("resubmit()")
# the search page is launched
def getProfDetail(userid):
#find section frist
title_type = "Type of Register"
title_place = "Primary/Principal Place of Practice"
#insert student information
count = tcm_detail.count()
if(userid<=count):
return
name = browser.find_by_css('.table-head')[0].text
reg_number = browser.find_by_xpath('//table/tbody/tr[1]/td[2]')[0].text
qulification = browser.find_by_xpath('//table/tbody/tr[2]/td[2]')[0].text
detail = {"_id":userid, "name":name, "qualification":qulification, "reg_number":reg_number}
tcm_detail.insert_one(detail)
#insert career info
示例11: DashboardTestCase
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_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))
示例12: __init__
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_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)
示例13: __init__
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
class GameInteraction:
def __init__(self):
self.browser = Browser('chrome')
currentFolderPath = os.path.dirname(os.path.abspath(__file__))
self.browser.visit("file:///"+currentFolderPath+"/2048-master/index.html")
def getGameState(self):
gameState = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] # empty gameState
tileContainer = self.browser.find_by_css(".tile-container")
allTiles = tileContainer.find_by_css(".tile")
sortedTiles = {}
classString = ".tile-position-"
legalPositions = {}
for col in xrange(1,5):
for row in xrange(1,5):
positionString = classString + str(col) + "-" + str(row)
legalPositions[str(col)+"-"+str(row)] = positionString
sortedTiles[str(col)+"-"+str(row)] = 0
#fill the sortedTiles map with all the tiles at their legal position (col-row)
for pos, classPos in legalPositions.items():
#time.sleep(0.3) #let the web browser catch up
currentTilesInPos = tileContainer.find_by_css(classPos)
if len(currentTilesInPos) == 1:
valueOfPos = currentTilesInPos[0].find_by_css(".tile-inner")[0].value.encode("utf8")
try:
valueOfPos = int(valueOfPos)
sortedTiles[pos] = valueOfPos
except:
pdb.set_trace()
print "[-]: valueOfPos (1 tile):",valueOfPos
elif len(currentTilesInPos) == 3:
#valueOfPos = currentTilesInPos.find_by_css(".tile-merged")[0].find_by_css(".tile-inner")[0].value.encode("utf8")
mergedTiles = tileContainer.find_by_css(classPos+".tile-merged")
innerTile = mergedTiles[0].find_by_css(".tile-inner")[0].value.encode("utf8")
try:
valueOfPos = int(innerTile)
sortedTiles[pos] = valueOfPos
except:
pdb.set_trace()
print "[-] mergedTiles:", mergedTiles
print "[-] innerTile:", innerTile
print "[-] valueOfPos (merged):",valueOfPos
else:
sortedTiles[pos] = 0
try:
for row in range(0,len(gameState)):
for col in range(0, len(gameState[row])):
tileLocation = str(col+1)+"-"+str(row+1)
gameState[row][col] = sortedTiles[tileLocation]
except:
pdb.set_trace()
return np.array(gameState)
def getScore(self):
score = self.browser.find_by_css(".score-container").value
print "[+] score:",score
splitScore = score.split("+")
return int(splitScore[0])
def move(self, action):
if action == "up":
self.browser.execute_script("KeyboardInputManager.moveUp()")
elif action == "down":
self.browser.execute_script("KeyboardInputManager.moveDown()")
elif action == "left":
self.browser.execute_script("KeyboardInputManager.moveLeft()")
elif action == "right":
self.browser.execute_script("KeyboardInputManager.moveRight()")
else:
print "[!] invalid action:", action
示例14: Tk
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
break
root = Tk()
root.withdraw()
dealFilePath = filedialog.askopenfilename()
if dealFilePath == '':
break
dealFileName = ntpath.basename(dealFilePath).replace('.xml','')
file = open(dealFilePath, 'r')
dealHtml = file.read()
file.close()
browser.execute_script("""var div = document.getElementsByTagName("form")[0];
div.innerHTML = '""" + dealHtml + """';""")
# # bkcenter & counterPartyTypeId
# nodeBkcenter = browser.find_by_name('bkCenter')
# nodeCounterPartyTypeId = browser.find_by_name('counterPartyTypeId')
# if businessType == "GBM":
# browser.execute_script("""var div = document.getElementsByName("counterPartyTypeId")[0];
# div.innerHTML = '""" + """<option value="1" selected="selected">Not Applicable</option>
# <option value="2">Bank/Bk Equ - Gen/Tier 1</option>
# <option value="3">Sovereign - Gen/Tiers 1/2</option>
# <option value="4">Bank/Bk Equ - Tier 2</option>
# <option value="5">Bank/Bk Equ - Tiers 3/4/5</option>
# <option value="6">Sovereign - Tier 3</option>
# <option value="7">Sovereign - Tiers 4/5</option>""".replace('\n','\t') + """';""")
# browser.execute_script("""var div = document.getElementsByName("bkCenter")[0];
# div.innerHTML = '""" + """<option value="BRAZIL">BRAZIL</option>
示例15: open
# 需要导入模块: from splinter import Browser [as 别名]
# 或者: from splinter.Browser import execute_script [as 别名]
with open('options.dump', 'rb') as dmp:
lastoptvalues = pickle.load(dmp)
lastoptkeys = ["county", "municipality", "workarea", "profession", "detailedprof"]
lastoptions = dict(zip(lastoptkeys, lastoptvalues))
print "Restoring last used options..."
browser = Browser('phantomjs', user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.15 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.15)"
browser.driver.set_window_size(1366, 768)
url = "http://www.arbetsformedlingen.se"
browser.visit(url)
browser.find_by_css('.sidhuvud .btn-login, .sidhuvud-globalmeny-sok .btn-group > .btn, .sidhuvud-globalmeny-sok .btn-group > .btn:first-child, .sidhuvud-globalmeny-sok .btn-group > .btn:last-child').click()
browser.find_by_css('.inloggnings-tabbar .nav-tabs li:nth-child(2) a ').click()
browser.fill("user", "[email protected]")
browser.fill("password",'Ejc2Tc6')
browser.execute_script('document.forms["konto"].submit()')
# locating the searchform
time.sleep(5) # waiing for the page to load
try:
browser.find_by_css('#mainTabMenu ul li:nth-child(1) a').click()
browser.find_by_css('.sv-text-portlet-content p.flikmeny a').click()
browser.find_by_css('.linkBold:nth-child(1)').click()
searchurl = browser.driver.current_url.replace("https", "http") # saving the url to the searchform for later
except AttributeError:
time.sleep(5) # wait a little longer
countyoptions = [c.value for c in browser.find_by_name('selectlistLan').find_by_tag('option')[1:]]