def download_by_website(login_url, path_list, base_url, browser_save_path, base_path): b = Browser(driver_name='chrome') b.visit(login_url) b.fill('username', 'hcqlztti') b.fill('password', 'S6rbiowsmhqit?') b.find_by_text('Sign In').click() for path in path_list: curr_url = base_url + path save_path = base_path + path b.visit(curr_url) file_list = b.find_by_id('row').first.find_by_tag( 'tbody').first.find_by_tag('tr') print len(file_list) for item in file_list: file_name = item.find_by_tag('td').first.text print file_name, '++++++++++++++++++' item.find_by_tag('td').first.click() file_path = os.path.join(browser_save_path, file_name) time.sleep(1) if os.path.exists(file_path): shutil.move(file_path, save_path) else: print file_name b.quit()
class hrmis(): username = '******' pwd = 'ESS3BUAT' mainUrl = "http://showcase.aishk.com:7701/HRMIS-UAT2/html/login.jsp" def __init__(self): self.driver_name = 'firefox' self.executable_path = 'E:/driver/geckodriver' self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.visit(self.mainUrl) def login(self): self.driver.fill('opCNA', self.username) self.driver.fill('pwd', self.pwd) self.driver.find_by_name('Submit').last.click() def selectRole(self, role): self.driver.find_by_text(role).last.click() def convertApp(self, url): ''' leave '../leave/index.jsp' ''' self.driver.find_link_by_href(url).last().click()
def login(self): b = Browser(driver_name='chrome') b.visit('https://vpn-guest.citicsinfo.com') b.fill('svpn_name', 'bj-dongsanhuan-1') b.fill('svpn_password', 'EQJtqXC2') b.find_by_text(u'登 录').click() time.sleep(2)
def main(): br = Browser('chrome') br.visit(URL) sleep(3) if br.is_text_present("Remember me", wait_time=7): br.fill('username', NAME) br.fill('password', PASSWORD) br.execute_script('javascript:savesettings()')
def main(): br = Browser('chrome') br.visit(URL) sleep(3) if br.is_text_present("Remember me", wait_time=7): br.fill('username', NAME) br.fill('password', PASSWORD) br.execute_script('javascript:savesettings()')
def main(): br = Browser('chrome') br.visit(URL) sleep(3) if br.is_text_present('Connection', wait_time=7): br.fill('login', '...') br.fill('password', '...') br.find_by_css('#logonForm_connect_button').first.click()
def main(): br = Browser('chrome') br.visit(URL) sleep(3) if br.is_text_present('Connection', wait_time=7): br.fill('login', '...') br.fill('password', '...') br.find_by_css('#logonForm_connect_button').first.click()
def test_create_a_shorten_url(self): browser = Browser() browser.visit('http://localhost:8000/') browser.fill('long_url', 'google.com') button = browser.find_by_id('btShorten') button.click() short_url = browser.find_by_id('short_url') self.assertEqual('http://localhost:8000/1', short_url.value)
def main(): browser = Browser() browser.visit('http://baidu.com') time.sleep(2) browser.fill('wd', 'python') button = browser.find_by_id("su") button.click() time.sleep(2) browser.driver.close()
def main(): br = Browser( 'chrome' ) #The Browser function takes the "Browser name" as an argument, it can be changed as per will. br.visit(URL) sleep(3) if br.is_text_present('Connection', wait_time=7): br.fill('login', NAME) br.fill('password', PASSWORD) br.find_by_css('#logonForm_connect_button').first.click()
def main(): br = Browser('firefox') br.visit(URL) sleep(3) #if br.is_text_present('Connection', wait_time=7): br.fill('UserName', USERNAME) br.fill('Password', PASSWORD) button = br.find_by_id("btnLogin") button.click() sleep(30) br.quit()
def main(): b = Browser('chrome') b.driver.set_window_size(1600, 1000) url = 'https://www.baidu.com/' b.visit(url) if b.is_text_present(u'关于百度'): print("yes, found it!") else: print("no, did not found it!") b.fill('wd', 'splink') third_found = b.find_by_id(u'su').click()
def main(): #br = Browser('chrome', executable_path='./chromedriver') br = Browser('chrome', executable_path='./chromedriver', headless=True) #print('opened') br.visit(URL) #print('visted') sleep(1) br.fill('user', NAME) br.fill('password', PASSWORD) br.find_by_name('Login').first.click() sleep(3)
def submit(self): b = Browser(driver_name="chrome") b.visit( "http://202.119.206.62/jwglxt/xtgl/login_slogin.html;jsessionid=6252CF2A6FB70A9D25A9B5ADD0A7C116" ) b.fill("yhm", self.txtUserName) b.fill("mm", self.TextBox2) button = b.find_by_id('dl') button.click() cookie = 'JSESSIONID' + '=' + b.cookies['JSESSIONID'] return cookie
def test_op(): print("hello world!") #browser = Browser("firefox")#模拟浏览器 browser = Browser("chrome")#模拟浏览器 #browser = Browser()#模拟浏览器 browser.visit("http://unptest.xiaobalei.com:5288/gbpayserver/mgr/")#访问指定URL browser.fill("name", "root") browser.fill("pwd", "111111") browser.find_by_value("登陆")[0].click() browser.find_by_text("计费应用管理").click() time.sleep(8) browser.quit()
def get_cookies(): # 模拟登录获取jsession,规避js加密算法 driver = Browser( driver_name='chrome', executable_path= 'C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe', headless=True) driver.visit(login_url) driver.fill('yhm', username) # name,value driver.find_by_id('mm').fill(password) driver.click_link_by_id('dl') for k, v in driver.cookies.all().items(): return v # 返回cookies
def test_op(): print("hello world!") #browser = Browser("firefox")#模拟浏览器 browser = Browser("chrome") #模拟浏览器 #browser = Browser()#模拟浏览器 browser.visit( "http://unptest.xiaobalei.com:5288/gbpayserver/mgr/") #访问指定URL browser.fill("name", "root") browser.fill("pwd", "111111") browser.find_by_value("登陆")[0].click() browser.find_by_text("计费应用管理").click() time.sleep(8) browser.quit()
def main(): executable_path = { 'executable_path': '/usr/lib/chromium-browser/chromedriver' } br = Browser('chrome', **executable_path) br.visit(URL) sleep(5) if br.is_text_present('Password', wait_time=7): br.fill('userpass', PASSWORD) br.find_by_css('#LoginButton').first.click() sleep(5) if br.is_text_present('Connect', wait_time=7): br.find_by_id('#netmode_mode').first.click() sleep(5)
def update_by_website(website_url, sql_file_name): b = Browser(driver_name='chrome') b.visit(website_url) # 登陆 b.fill('username', 'admin') b.fill('password', 'admin') code = b.find_by_id('code')[0].text b.fill('code', code) b.find_by_text('Log in!').click() time.sleep(5)
def Login(username, password): browser = Browser() # Find cache direction browser.visit('about:cache') json_dir = browser.html json_dir = json_dir.split('<th>Storage disk location:</th>')[2].split('</td>')[0].split('<td>')[1].replace(' ', '') + "\\entries\\" print(json_dir) # Login time.sleep(2) browser.visit(url) print('Trying Login...') time.sleep(8) browser.fill('user', username) browser.fill('pass', password) url1 = browser.url print(browser.url) try: browser.find_by_id('loginButton').click() except Exception as e: WriteLog(e) browser.forward() times = 0 while True: time.sleep(10) if len(browser.url) > 30: break times += 1 if times < 4: info = 'The email or password you entered is incorrect' if browser.is_text_present(info): WriteLog(info + ' [' + username + '----' + password + ']') WriteFailed(username + '\t' + password + '\n') browser.quit() return if times == 3: print('Login timeout') WriteLog('Login timeout: ' + '[' + username + '----' + password + ']') browser.quit() return print('.\t') WriteLog('[' + username + '] login succeed!') print('succeed! Get Json...') time.sleep(45) cook = browser.cookies.all() GetJson(username, json_dir, cook) browser.quit()
def main(): from splinter.browser import Browser browser = Browser() browser.visit('http://google.com') browser.fill('q', 'splinter - python acceptance testing for web applications') browser.find_by_css('.lsb').first.click() if browser.is_text_present('splinter.cobrateam.info'): print "Yes, the official website was found!" else: print "No, it wasn't found... We need to improve our SEO techniques" #browser.execute_script("var win = window.open(); win.document.write('<html><head><title>Generated HTML of ' + location.href + '</title></head><pre>' + document.documentElement.innerHTML.replace(/&/g, '&').replace(/</g, '<') + '</pre></html>'); win.document.close(); void 0;") browser.quit()
def enter_discussion(name, code, pwd): b = Browser() b.visit(HOST_NAME) # login in b.fill('name', name) b.fill('code', code) b.fill('pwd', pwd) b.find_by_name('submit').first.click() # choose b.choose('classroom_id', '2') b.choose('course_id', '2') b.find_by_name('submit').first.click() # enter discuss-detail b.visit(HOST_NAME + '/discuss-detail_25')
def main(): # browser = Browser('chrome') browser = Browser() browser.visit(PE_LOGIN) browser.fill('username', USERNAME) browser.fill('password', PASSWORD) button = browser.find_by_name('login') button.click() browser.visit(PE_COUNTRIES) f = open("/tmp/stat.html", "w") print >> f, browser.html f.close() browser.quit() print '__END__'
def main(): # browser = Browser('chrome') browser = Browser() browser.visit(PE_LOGIN) browser.fill('username', USERNAME) browser.fill('password', PASSWORD) button = browser.find_by_name('login') button.click() browser.visit(PE_COUNTRIES) f = open("/tmp/stat.html", "w") print >>f, browser.html f.close() browser.quit() print '__END__'
def update_by_website(website_url, sql_file_name): b = Browser(driver_name='chrome') b.visit(website_url) # 登陆 b.fill('username', 'admin') b.fill('password', 'admin') code = b.find_by_id('code')[0].text b.fill('code', code) b.find_by_text('Log in!').click() # 切换至'工具列表'--》'数据库更新' b.find_link_by_href('/tool_list/eod_tools').click() b.find_by_id('sql_file_name').fill(sql_file_name) b.find_by_id('update_database_btn').click() time.sleep(5)
class AcceptanceUploader(unittest.TestCase): def setUp(self): self.browser = Browser() self.local_file = os.path.join(os.path.dirname(__file__), "sample_frame.jpg") """ This test uses webdriver to navigate to home app url, and select a localfile and make a upload of this file, then check if 'Uploaded to Here' link is visible after upload reaches 100%. We need to start up our server over port 8888 to webdriver navigate """ def test_upload_from_localfile(self): self.browser.visit('http://localhost:8888/') self.assertTrue(self.browser.is_text_not_present("Uploaded to Here")) self.browser.attach_file('datafile', self.local_file) while not self.browser.is_text_present('Uploaded to Here'): pass self.assertTrue(self.browser.is_text_present("Uploaded to Here")) """ This test uses webdriver to navigate to home app url, and select a localfile and make a upload of this file when the upload is complete type a description send post the form, so check if follow a redirect to detail page and the description is correct. We need to start up our server over port 8888 to webdriver navigate """ def test_upload_from_localfile_and_fill_description(self): self.browser.visit('http://localhost:8888/') self.browser.attach_file('datafile', self.local_file) self.browser.fill('description', 'Uploading file simulate clientside navigation') while not self.browser.is_text_present('Uploaded to Here'): pass button = self.browser.find_by_id('savebutton').first button.click() self.assertTrue(self.browser.is_text_present('Super Upload Detail Page')) self.assertTrue(self.browser.is_text_present('Uploading file simulate clientside navigation')) def tearDown(self): self.browser.quit()
def loginFunc(): browser = Browser("chrome") browser.visit(login_url) # 找到登陆按钮点击 #browser.find_by_text(u"登录").click() #输入用户密码 browser.fill("smsQuick", login_name) browser.find_by_id("pwQuickLogin").fill(login_pass) browser.find_by_id("quick_login").click() while True: #判断当前的url是否已经进入系统 if browser.url != loginOk_url: sleep(1) else: break #进入所需挂号页面 browser.visit(loginNeed_url) while True: #判断当前的url是否已经进入系统 if browser.url != loginNeed_url: sleep(1) else: break # 开始循环检查是否有票 while True: #判断当前的url是否已经进入系统 if not FindPiao(browser): sleep(1) browser.reload() else: break while True: if browser.url.find("http://www.bjguahao.gov.cn/order/confirm") < 0: sleep(0.1)
def search_click(): browser = Browser('firefox', profile='fraudbot') # Visit URL url = "http://www.google.com" browser.visit(url) browser.fill('q', "karmachamillionaire") time.sleep(1) # Find and click the 'search' button button = browser.find_by_name("btnG") # Interact with elements button.click() time.sleep(2) if browser.is_text_present("did not match any documents"): print "nobody likes us =(" else: print "we're popular =)" browser.quit()
def main(): browser = Browser() #browser = Browser('zope.testbrowser') #when you want it to run in the background browser.visit(url) browser.fill('u_id', username) browser.fill('u_pw', password) browser.find_by_name('submit')[0].click() browser.find_link_by_text('here')[0].click() if browser.find_by_name('tran[1]_agree'): browser.check('tran[1]_agree') browser.check('tran[1]_fj1') browser.find_by_name('tran[1]_sched')[0].click() browser.fill('tran[1]_CALLNUM', callnumber) browser.find_by_name('tran[1]_act')[1].click() if browser.is_text_present('%s is full' % callnumber): print '%s full :(' % callnumber else: browser.find_by_name('tran[1]_act')[0].click() print 'happy times! enrolled in %s' % callnumber subprocess.call('crontab -r', shell=True) browser.quit() print '__END__'
class TestAcceptance(unittest.TestCase): def setUp(self): self.browser = Browser() def test_add_an_expense(self): self.browser.visit('http://localhost:8000/') self.browser.fill('value', '20.0') self.browser.fill('category', 'food') self.browser.fill('description', 'Rice') self.browser.fill('date', '01/01/2011') self.browser.find_by_id('submit').first.click() self.browser.is_text_present('Expense saved with success!') |should| be(True) def tearDown(self,): self.browser.quit()
def crack(): global b #使用splinter打开chrome浏览器 b = Browser(driver_name="chrome") b.visit(url) try: count = 0 while b.url == url: pwd=f.readline().strip() print (pwd); if not pwd: print ('字典已比对完。') break b.fill('password',pwd); b.find_by_id(u"loginSub").click(); count +=1 print (u"循环破解... 第 %s 次" % count) notify.Beep(300, 3000); notify.MessageBoxW('破解','搞定了') print (u"快看 啊") except Exception as e: print(traceback.print_exc())
def login_booking(netidname, netidpwd): b = Browser() b.visit('http://gym.sysu.edu.cn/index.html') login = b.find_link_by_href("javascript:login();") # 找到登录按钮 login.click() # 输入账号密码和验证码 b.fill('username', netidname) b.fill('password', netidpwd) validcode = raw_input( 'Please here enter the verification code of login interface manually:') b.fill('captcha', validcode) b.find_by_name('submit').click() # 点击登录按钮 return b
class ProcessOn(): def __init__(self, url): try: self.driver_name = 'chrome' self.executable_path = '/usr/local/bin/chromedriver' self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(800, 800) self.driver.visit(url) self.driver.cookies.delete("processon_userKey") self.driver.find_by_text(u"注册").click() sleep(1) if self.driver.url == 'https://www.processon.com/signup': return except Exception as e: print(e) self.driver.quit() def getrandomstr(self): randomstr = str(random.randint(1000000, 9999999)) return randomstr def signup(self, email): try: self.driver.fill("email", email) self.driver.fill("pass", self.getrandomstr()) self.driver.fill("fullname", self.getrandomstr()) self.driver.find_by_text(u"点击验证").click() print("\r请手动输入验证码") while True: if self.driver.url != 'https://www.processon.com/signup/submit': sleep(1) else: self.driver.cookies.delete() self.driver.quit() break except Exception as e: print(e) self.driver.quit()
from splinter.browser import Browser ticket = Browser(driver_name = 'chrome') ticket.visit('http://www.zhihu.com/') ## xx.fill("wd", "dataman")即可在搜索栏搜索dataman ## button = xx.find_by_value(u"提问") button = ticket.find_by_id(u"zu-top-add-questionSBSBSBSBSBSBSB") # ================================================================================================ # 12306抢票 # ================================================================================================ from splinter.browser import Browser client = Browser(driver_name= 'chrome') url = 'https://kyfw.12306.cn/otn/leftTicket/init' client.visit(url) client.find_by_text(u'登录').click() client.fill('loginUserDTO.user_name','*****@*****.**') client.fill("userDTO.password","family40440412306") #填写出发点目的地 client.cookies.add({"_jc_save_fromStation":"%u4E0A%u6D77%2CSHH"}) client.cookies.add({"_jc_save_fromDate":"2016-01-20"}) client.cookies.add({u'_jc_save_toStation':'%u6C38%u5DDE%2CAOQ'}) #加载查询 client.reload() client.find_by_text(u"查询").click() #预定 client.find_by_text(u"预订")[1].click() #选择乘客 client.find_by_text(u"数据分析侠")[1].click() #-*- coding:utf-8 -*- #京东抢手机脚本
#-*- coding: UTF-8 -*- from splinter.browser import Browser b = Browser(driver_name="chrome") # b.visit("http://www.baidu.com") # b.fill("wd", "splinter") # button = b.find_by_value(u"百度一下") # button.click() b.visit("https://kyfw.12306.cn/otn/login/init") b.find_by_text(u"登录").click() username="******" passwd="12306_com_" b.fill("loginUserDTO.user_name", username) # username部分输入自己的账号 b.fill("userDTO.password", passwd) # passwd部分输入账号密码 b.cookies.add({"_jc_save_fromDate":"2016-02-13"}) # 此处添加出发日期 b.cookies.add({"_jc_save_fromStation":"%u6210%u90FD%2CCDW"}) # 此处添加出发地 b.cookies.add({u'_jc_save_toStation':'%u676D%u5DDE%2CHZH'}) # 此处添加目的地 b.cookies.all() b.find_by_text(u"查询").click() b.find_by_text(u"预订")[1].click() # 下标1表示买的是可选班次的第二班车
#!usr/bin/python from splinter.browser import Browser import re import time br = Browser() br.visit("http://www.160by2.com/Index") br.fill('username', 'YOUR_PHONE_NUMBER_USED_TO_CREATE_160BY2_ACCOUNT') br.fill('password', 'YOUR_ACCOUNT_PASSWORD') button = br.find_by_name("") button.click() stringurl = br.url stringurl2 = stringurl.split("id=", 1)[1] id = stringurl2.split("id=", 1)[1] jsstring = "window.parent.openPage('SendSMS?id=" + id + "', 'aSendSMS', 'aSMS', 'ulSMS')" br.execute_script(jsstring) time.sleep(8) br.execute_script(jsstring) print "JS Executed" time.sleep(8) with br.get_iframe('by2Frame') as iframe: iframe.fill( "sendSMSMsg", "Well, I guess robot's do send SMSes when spandan wants them to ;)") iframe.find_by_tag("input")[10].fill( "THE_PHONE_NUMBER_YOU_WANT_TO_SEND_SMS_TO") button2 = iframe.find_by_id("btnsendsms").first print button2.value button2.click()
class Ticket(object): def __init__(self, config_file): ## config parser setting self.config_file = config_file self.settings = configparser.ConfigParser() self.settings._interpolation = configparser.ExtendedInterpolation() self.settings.read(self.config_file,'utf-8') ## environment setting self.brower='chrome' self.b = Browser(driver_name=self.brower) self.station={} self.url = "https://kyfw.12306.cn/otn/leftTicket/init" # 席别类型(对应列标号) self.ticket_index = [ '', u'商务座', u'特等座', u'一等座', u'二等座', u'高级软卧', u'软卧', u'硬卧', u'软座', u'硬座', u'无座' ] self.username = '' self.password = '' self.date_format='%Y-%m-%d' self.tolerance = -1 self.blacklist = {} self.date = [] self.isStudent = False self.success = 0 self.find_ticket = 0 self.config_parser() self.playmusic = False self.count = 0 def ConfigSectionMap(self,section): dict1 = {} options = self.settings.options(section) for option in options: try: dict1[option] = self.settings.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1 def daterange(self, start_date, end_date): for n in range(int ((end_date - start_date).days) + 1): yield start_date + timedelta(n) def config_parser(self): if self.retrieve_station_dict() == -1: sys.exit() if self.retrieve_book_options() == -1: sys.exit() def retrieve_station_dict(self): dict_helper=self.ConfigSectionMap('STATIONCOOKIE') for name, value in dict_helper.iteritems(): self.station[name]=value def retrieve_book_options(self): login_info=self.ConfigSectionMap('GLOBAL') self.username = login_info['username'].strip() self.password = login_info['password'].strip() self.brower = login_info['browser'] book_settings = self.ConfigSectionMap('TICKET') self.fromStation = [ station.strip() for station in book_settings['from_station'].split(',')] self.toStation = [ station.strip() for station in book_settings['to_station'].split(',')] trains = [ train.strip() for train in book_settings['trains'].split(',')] if len(trains) == 1 and trains[0] == '': self.trains = [] else: self.trains = trains self.ticket_type =[ _type.strip() for _type in book_settings['ticket_type'].split(',')] rangeQuery = book_settings['range_query'].strip() if rangeQuery == 'Y': date = [ d.strip() for d in book_settings['date'].split(',')] if len(date) < 2: print "未设置正确的起至时间" return -1 else: start_date = datetime.strptime(date[0],self.date_format) end_date = datetime.strptime(date[1],self.date_format) if end_date < start_date: print "查询截止日期不可大于开始日期!" return -1 for single_date in self.daterange(start_date, end_date): self.date.append(single_date.strftime(self.date_format)) else: self.date = [ d.strip() for d in book_settings['date'].split(',')] if book_settings['student'].strip() == 'Y': self.isStudent = True self.tolerance = int(book_settings['tolerance']) self.people = [ people.strip() for people in book_settings['people'].split(',') ] if book_settings['alarm'].strip() == 'Y': self.playmusic = True def login(self): self.b.visit(self.url) self.b.find_by_text(u"登录").click() self.b.fill("loginUserDTO.user_name",self.username) self.b.fill("userDTO.password",self.password) pdb.set_trace() def page_has_loaded(self): page_state = self.b.evaluate_script("document.readyState") return page_state == 'complete' def switch_to_order_page(self): order = [] while len(order) == 0: order = self.b.find_by_text(u"车票预订") order[0].click() def checkTicket(self, date, fromStation, toStation): print 'date: %s, from %s, to %s'%(date, fromStation, toStation) self.b.cookies.add({"_jc_save_fromDate":date}) self.b.cookies.add({"_jc_save_fromStation":self.station[fromStation]}) self.b.cookies.add({"_jc_save_toStation":self.station[toStation]}) self.b.cookies.all() self.b.reload() if self.isStudent: self.b.find_by_text(u'学生').click() self.b.find_by_text(u"查询").click() all_trains = [] while self.page_has_loaded() == False: continue while len(all_trains) == 0: all_trains = self.b.find_by_id('queryLeftTable').find_by_tag('tr') for k, train in enumerate(all_trains): tds = train.find_by_tag('td') if tds and len(tds) >= 10: has_ticket= tds.last.find_by_tag('a') if len(has_ticket) != 0: if k + 1 < len(all_trains): this_train = all_trains[k+1]['datatran'] if len(self.trains) != 0 and this_train not in self.trains: continue if self.tolerance != -1 and this_train in self.blacklist and self.blacklist[this_train] >= self.tolerance: print u"%s 失败 %d 次, 跳过"%(this_train, self.blacklist[this_train]) continue for cat in self.ticket_type: if cat in self.ticket_index: i = self.ticket_index.index(cat) else: print '无效的席别信息' return 0, '' if tds[i].text != u'无' and tds[i].text != '--': if tds[i].text != u'有': print u'%s 的 %s 有余票 %s 张!'%(this_train, cat ,tds[i].text) else: print u'%s 的 %s 有余票若干张!'%(this_train, cat) self.find_ticket = 1 tds.last.click() break if self.find_ticket: break return this_train def book(self): while self.page_has_loaded() == False: continue if len(self.people) == 0: print '没有选择乘车人!' return 1 more = [] while len(more) == 0: more = self.b.find_by_text(u"更多") more[0].click() person = [] people = self.people while len(person) == 0: person=self.b.find_by_xpath('//ul[@id="normal_passenger_id"]/li/label[contains(text(),"%s")]'%people[0]) for p in people: self.b.find_by_xpath('//ul[@id="normal_passenger_id"]/li/label[contains(text(),"%s")]'%p).click() if self.b.find_by_xpath('//div[@id="dialog_xsertcj"]').visible: self.b.find_by_xpath('//div[@id="dialog_xsertcj"]/div/div/div/a[text()="确认"]').click() return 1 def ring(self): pygame.mixer.pre_init(64000, -16, 2, 4096) pygame.init() pygame.display.init() screen=pygame.display.set_mode([300,300]) #pygame.display.flip() pygame.time.delay(1000)#等待1秒让mixer完成初始化 tracker=pygame.mixer.music.load("media/sound.ogg") #track = pygame.mixer.music.load("sound.ogg") pygame.mixer.music.play() # while pygame.mixer.music.get_busy(): #pygame.time.Clock().tick(10) running = True img=pygame.image.load("media/img.jpg") while running: screen.blit(img,(0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type==pygame.QUIT: running = False pygame.quit () return 1 def executor(self): self.login() self.switch_to_order_page() while self.success == 0: self.find_ticket = 0 while self.find_ticket == 0: for date in self.date: try: self.count += 1 print "Try %d times" % self.count for fromStation in self.fromStation: for toStation in self.toStation: this_train = self.checkTicket(date, fromStation, toStation) if self.find_ticket: break if self.find_ticket: break if self.find_ticket: break except KeyboardInterrupt: self.b.find_by_text(u'退出').click() sys.exit() except: continue # book ticket for target people self.find_ticket = 0 while self.find_ticket == 0: try: self.find_ticket = self.book() except KeyboardInterrupt: self.b.find_by_text(u'退出').click() sys.exit() except: continue if self.playmusic: self.ring() print "订票成功了吗?(Y/N)" input_var = '' while input_var == '': input_var= sys.stdin.read(1) if input_var == 'Y' or input_var == 'y': self.success = 1 elif input_var == 'N' or input_var == 'n': if this_train in self.blacklist: self.blacklist[this_train] += 1 else: self.blacklist[this_train] = 1 print u"%s 失败 %d 次"%(this_train, self.blacklist[this_train]) self.b.back() self.b.reload() else: input_var = '' continue self.b.find_by_text(u'退出').click()
class Redmine(object): def __init__(self, url, login, password, project, custom_project_params=None): """ This will open redmine page, and then login url: your redmine url login: your redmine login password: your redmine password project: the id of your project custom_project_params: some custom parameters to pass into projects url, in order to create a new issue """ if not url.endswith('/'): url += '/' self._url = url self._login = login self._password = password self._project = project self._custom_project_params = custom_project_params self._browser = Browser() self._do_login() def _do_login(self): self._browser.visit(self._url + LOGIN_URL) self._browser.fill('username', self._login) self._browser.fill('password', self._password) self._browser.find_by_name('login').first.click() def create_issue(self, stop_before_commit=False, **issue_fields): """ Create a new issue into your redmine. This is an awesome (crazy) method. Pay attention: - You need to pass at least the required fields of your redmine. * For instance, if my redmine requires a title, and this field has the name: 'issue[subject]' than I must pass my title as follows: create_issue(subject='My name') - You can also pass the name of other fields you'd like to fill, remembering to just pass the inner content of the field's name. For example, in this case: 'issue[another_field]' The parameter would be: create_issue(another_field='My content') - As an example, in a default Redmine, I think this are the default required parameters that you must pass: create_issue(tracker_id, subject, description, assigned_to_id, start_date, due_date, estimated_hours) - stop_before_commit is a flag, used when you have some extra fields that are not yet handled by this method, so you need to deal with it by hand. In this cases, call this method like this: create_issue(do_not_commit=True) And the method will just fill the fields you passed, without clicking 'commit' button. - IMPORTANT: Scenarios that contains custom fields are also covered. A custom field has its name as something like: 'issue[custom_field_values][20]' In this cases, you must pass a 'custom_field_values' parameter as a dict, where the key is the number of the field, and the value is the content you want. In this example, the parameter would be as follows: create_issue(custom_field_values={'20': 'My content'}) Then the method will do the rest. """ new_issue_url = self._url + PROJECT_TAG + '/' + self._project + '/issues/new' if self._custom_project_params: new_issue_url += '?%s' % self._custom_project_params self._browser.visit(new_issue_url) def fill_custom_field(field_id, field_value): for custom_field_number, custom_field_value in field_value.items(): self._browser.fill(ISSUE_TAG + '[%s][%s]' % (field_id, custom_field_number), custom_field_value) for field_id, field_value in issue_fields.items(): if type(field_value) == type({}): fill_custom_field(field_id, field_value) else: self._browser.fill(ISSUE_TAG + '[%s]' % field_id, field_value) if not stop_before_commit: self._browser.find_by_name('commit').first.click() # TODO: find 'task_id' to return # (the last number under page url may be this) def fill_time(self, issue_id, start_date, end_date, time_per_day): """ Fill time into some issue that already exists. issue_id: id of the existing issue start_date: date to start filling in time end_date: date to end filling in time (self-including) - Pass start and end date as YYYY-MM-DD format, like on this example: fill_time(1, start_date="2011-04-23", end_date="2011-04-27", 4) Following this example, after method is run, the issue with id '1' will have, from monday to friday (2011/04/23, 2011/04/27), a new working time, with value 4 (4 hours), with a total of 20 hours worked on the week. """ def discover_working_days(start_date, end_date, time_per_day): # format date start_date = strptime(start_date, '%Y-%m-%d') end_date = strptime(end_date, '%Y-%m-%d') # convert date to datetime start_date = datetime.date(start_date.tm_year, start_date.tm_mon, start_date.tm_mday) end_date = datetime.date(end_date.tm_year, end_date.tm_mon, end_date.tm_mday) working_days = [] total_number_of_days = (end_date - start_date).days + 1 current_date = start_date for day in range(total_number_of_days): if current_date.isoweekday() in range(1, 6): # working day [1,2,3,4,5] date = current_date.strftime('%Y-%m-%d') working_days.append((date, time_per_day)) current_date = datetime.timedelta(days=1) + current_date return working_days working_days = discover_working_days(start_date, end_date, time_per_day) # like: [("2011-03-14", 4), ("2011-03-15", 4), .....] new_time_url = self._url + ISSUE_TAG + 's/' + issue_id + '/' + TIME_URL for date, hour in working_days: self._browser.visit(new_time_url) self._browser.fill(TIME_TAG + '[spent_on]', str(date)) # "2011-03-14" self._browser.fill(TIME_TAG + '[hours]', str(hour)) self._browser.find_by_name('commit').first.click() def close_issue(self, issue_id): issue_url = ISSUE_TAG + 's/' + issue_id self._browser.open(self._url + issue_url) self._browser.find_link_by_partial_href(issue_url + '/edit').first.click() self._browser.select(ISSUE_TAG + '[done_ratio]', "label=100 %") self._browser.select(ISSUE_TAG + '[status_id]', "label=Resolvido") self._browser.find_by_name('commit').first.click()
from splinter.browser import Browser b = Browser(driver_name="chrome") url = 'https://kyfw.12306.cn/otn/leftTicket/init' b = Browser(driver_name="chrome") b.visit(url) b.find_by_text(u"登录").click() b.fill("loginUserDTO.user_name","xxxx") b.fill("userDTO.password","xxxx") b.cookies.all() {u'BIGipServerotn': u'1977155850.38945.0000', u'JSESSIONID': u'0A01D97598F459F751C4AE8518DBFB300DA7001B67', u'__NRF': u'95D48FC2E0E15920BFB61C7A330FF2AE', u'_jc_save_fromDate': u'2018-02-22', u'_jc_save_fromStation': u'%e5%b0%9a%e5%bf%97', u'_jc_save_toStation': u'%e6%9d%ad%e5%b7%9e', u'current_captcha_type': u'Z'} b.cookies.add({"_jc_save_fromStation":"%e5%b0%9a%e5%bf%97"}) 添加出发日期 b.cookies.add({"_jc_save_fromDate":"2018-02-22"}) 添加目的地 b.cookies.add({u'_jc_save_toStation':'%e6%9d%ad%e5%b7%9e'}) b.reload() b.find_by_text(u"查询").click() autoSearchTime=1000
#button=b.find_by_id(u'su') #button.click()#模拟点击百度一下 #if b.is_text_present('splinter.cobrateam.info'): # print 'True' #else: # b.quit() username = u'*****@*****.**' passwd = u'020002118_' zz = u'%u67A3%u5E84%2CZEK' sh = u'%u4E0A%u6D77%2CSHH' dtime = u'2016-02-14' order = 0 passenger = u'钟啸林' b.find_by_text(u'登录').click() #这里的by text和前面的by value,by id差不多 sleep(3) b.fill("loginUserDTO.user_name", username) b.fill("userDTO.password", passwd) #这里需要通过F12来寻找<input中的name对应的 print u'wait for you to input the 验证码....' while True: if b.url != initmy_url: sleep(1) else: break print(u'跳回购票页面....') b.visit(ticket_url) b.cookies.add({'_jc_save_fromStation': zz}) b.cookies.add({'_jc_save_toStation': sh}) b.cookies.add({'_jc_save_fromDate': dtime}) b.reload() sleep(2)
from splinter.browser import Browser print "hello twitter" handle = raw_input('twitter handle:') #pw = raw_input('password:'******'firefox') browser.visit('https://twitter.com/') loginbutton = browser.find_by_text('Log In') loginbutton.first.click() #works up till here usernamebox = browser.find_by_id('signin-email') #passwordbox = browser.find_by_id('signin-password') if len(usernamebox)==0: print "no username boxes found =^[" browser.fill(usernamebox.first, handle) #browser.fill(passwordbox.first, pw)
#-*- coding: utf-8 -*- #coding=utf-8 from splinter.browser import Browser b = Browser() b.visit("http://www.baidu.com") ### b.fill("wd","splinter") button = b.find_by_id('su') button.click()
class Redmine(object): activities_codes = {'Funcionalidade': '36', 'Codificacao': '25'} type_codes = {'Funcionalidade': '2', 'Codificacao': '7', 'Refatoramento': '14'} participants_code = {'59':'Douglas Camata', '65': 'Felipe Norato Lacerda', '60': 'Fernando Carvalho', '149': 'Fábio Ribeiro', '68': 'Priscila Manhaes da Silva', '32': 'Rogério Atem'} def __init__(self): self.username = raw_input('Digite seu usuário: ') self.password = encode(getpass('Digite sua senha: ')) self.prepare() def prepare(self): try: self.browser = Browser('chrome') except: self.browser = Browser() self.login() def login(self): self.browser.visit('http://sgsetec.renapi.gov.br/login') self.browser.fill('username', self.username) self.browser.fill('password', decode(self.password)) self.browser.find_by_name('login').click() def visit_project(self, project_id): self.browser.visit('http://sgsetec.renapi.gov.br/kanban?project_id=%s' % project_id) def create_issue(self, project_id, type_name, title, description, begin, end, participants, monitors): self.browser.visit('http://sgsetec.renapi.gov.br/projects/%s/issues/new' % project_id) self.browser.select('Tipo', self.type_codes[type_name]) self.browser.fill('issue[subject]', title) self.browser.fill('issue[description]', description) self.browser.fill('issue[start_date]', begin) self.browser.fill('issue[due_date]', end) for participant in participants: self.browser.select('Participantes', self.participants_code[participant]) for monitor in monitors: self.browser.select('Monitores', self.participants_code[monitor]) self.browser.find_by_value('Criar').click() def update_issue(self, issue_id, activity, date, worked_hours=4, comment=None): self.browser.visit('http://sgsetec.renapi.gov.br/issues/%s/time_entries/new' % issue_id) self.browser.fill('time_entry[spent_on]', date) self.browser.find_by_id('time_entry_hours').fill(worked_hours) self.browser.select('time_entry[activity_id]', self.activities_codes[activity.capitalize()]) self.browser.find_by_value('Salvar').click() def finish_issue(self, issue_id, begin, total_days, activity): #do not need to plus um day into cause first day of work is 'begin' day_worked = 0 while day_worked < total_days: date = datetime.datetime.strptime(begin, "%Y-%m-%d") date = date.date() + datetime.timedelta(day_worked) day_worked += 1 if date.weekday() > 4: total_days += 1 continue date = date.date() + datetime.timedelta(day_worked) self.update_issue(issue_id=issue_id, date=str(date), activity=activity) self.close_issue(issue_id) def close_issue(self, issue_id): self.browser.visit('http://sgsetec.renapi.gov.br/issues/%s/time_entries/new' % issue_id) self.browser.select('issue[status_id]', '3') self.browser.select('issue[done_ratio]', '100') self.browser.find_by_value('Salvar').click()
#browsername = 'chrome' # 'chrome' need browser drivers browsername = 'firefox' # 'firefox' is better passenger_id = 'normalPassenger_0' ''' # find cookies with devtools of browsers ''' cookiedict_update = {"_jc_save_fromDate":"2016-02-01", "_jc_save_fromStation":"%u53A6%u95E8%2CXMS", "_jc_save_toStation":"%u5317%u4EAC%2CBJP", } brs = Browser(driver_name=browsername) brs.visit(site) brs.find_by_id(u'login_user').click() brs.fill('loginUserDTO.user_name', loginname) brs.fill('userDTO.password', loginpass) #sleep(10) input("Press Enter to continue...") # choose picture here ''' # jump to ticket order page ''' brs.find_by_id(u'selectYuding').click() brs.cookies.add(cookiedict_update) print(brs.cookies.all()) brs.reload() brs.find_by_id(searchtype_id).click() brs.find_by_id(u'query_ticket').click() brs.find_by_text(u"预订")[1].click()
import time from splinter.browser import Browser # Se eu não passar nenhum driver, Browser(), # o padrão já será o firefox. browser = Browser('firefox') url = "http://douglasmiranda.com" # Na linha abaixo eu visito a url, # é neste momento em que o browser se abrirá browser.visit(url) # com o método fill eu preencho o campo de formulário, # ele encontra este campo pelo atributo name do input # para interagir com elementos veja mais formas em: # http://splinter.cobrateam.info/docs/elements-in-the-page.html palavra_chave = "python" browser.fill('q', palavra_chave) # estou inserindo este delay aqui porque ao preencher o campo de busca # há uma animação no botão "Pesquisar", este é o tempo para que # a animação esteja completa e o botão esteja clicável # que é um ponto importante, pois o objeto precisa estar visível para # que ele possa ser clicado time.sleep(0.2) # Encontrando o botão de submit do formulário # que é um <input type="submit"... dentro de um # formulário que tem o id="search-form" # por um seletor CSS, se você é familiarizado # com CSS vai achar bem simples o uso # mais formas de encontar elementos na página em: # http://splinter.cobrateam.info/docs/finding.html
#button=b.find_by_id(u'su') #button.click()#模拟点击百度一下 #if b.is_text_present('splinter.cobrateam.info'): # print 'True' #else: # b.quit() username=u'*****@*****.**' passwd=u'020002118_' zz=u'%u67A3%u5E84%2CZEK' sh=u'%u4E0A%u6D77%2CSHH' dtime=u'2016-02-14' order=0 passenger=u'钟啸林' b.find_by_text(u'登录').click()#这里的by text和前面的by value,by id差不多 sleep(3) b.fill("loginUserDTO.user_name",username) b.fill("userDTO.password",passwd)#这里需要通过F12来寻找<input中的name对应的 print u'wait for you to input the 验证码....' while True: if b.url!=initmy_url: sleep(1) else: break print(u'跳回购票页面....') b.visit(ticket_url) b.cookies.add({'_jc_save_fromStation':zz}) b.cookies.add({'_jc_save_toStation':sh}) b.cookies.add({'_jc_save_fromDate':dtime}) b.reload() sleep(2)
""" interact with forms, test if element exists in a page This example: - Try to login on Google Accounts - do this over and over again - until the captcha appear Just for try if after many attempts to login, Google show the captcha for the safe of the system. """ from splinter.browser import Browser browser = Browser('chrome') browser.visit('https://www.google.com/accounts/ServiceLogin') # just a counter i = 0 # while not appear the captcha input, try login with wrong account while True: browser.fill('Email', 'my_wrong_username') browser.fill('Passwd', 'my_wrong_password') browser.find_by_css('#signIn').first.click() i += 1 if browser.is_element_present_by_id('logincaptcha'): break print 'After', i, 'attempts the captcha appeared!'
class TestOpenstackDashboard(tests.FunctionalTest): def setUp(self): self.browser = "" def tearDown(self): self.browser = "" def _logIn(self): self.browser.visit("http://%s" % self.config['dash']['host']) self.browser.fill('username', self.config['dash']['admin_user']) self.browser.fill('password', self.config['dash']['admin_pass']) button = self.browser.find_by_id('home_login_btn') button.click() def _logOut(self): drop_button = self.browser.find_by_id("drop_btn") drop_button.click() logout = self.browser.find_link_by_href("/auth/logout/") logout.click() def lookForError(self): self.assertFalse(self.browser.is_text_present("Error")) def validateOverview(self): self.assertTrue(self.browser.is_text_present("Cores"), "CPU Status is not showing properly") self.assertTrue(self.browser.is_text_present("RAM"), "RAM Status is not showing properly") self.assertTrue(self.browser.is_text_present("Disk"), "Disk Status is not showing properly") # @tests.skip_test("--Skipping--") def test_overview_page(self): self.browser = Browser() self._logIn() overview = self.browser.find_link_by_text("Overview") overview.click() self.lookForError() self.validateOverview() self._logOut() self.browser.quit() @tests.skip_test("--Skipping--") def test_instances_page(self): self.browser = Browser() self._logIn() instances = self.browser.find_link_by_text("Instances") instances.click() self.lookForError() self._logOut() self.browser.quit() def test_adding_a_keypair(self): self.browser = Browser() self._logIn() keypair = self.browser.find_link_by_text("Keypairs") keypair.click() self.lookForError() keypair_btn = self.browser.find_by_id("keypairs_create_link") keypair_btn.click() self.browser.fill('name', "test_keypair_test") # Create Keypair in d5 button = self.browser.find_by_value('Add Keypair') button.click() return_link = self.browser.find_link_by_partial_text("Return to keypairs") return_link.click() self.assertTrue(self.browser.is_text_present("test_keypair_test"), "Created keypair not found") delete_link = self.browser.find_by_id("delete_test_keypair_test") delete_link.click() # accept the js alert alert = self.browser.get_alert() alert.accept() # verify delete message self.assertTrue(self.browser.is_text_present( "Successfully deleted keypair: test_keypair_test"), "Keypair not successfully deleted") self._logOut() self.browser.quit()
from bypy import ByPy from splinter.browser import Browser from time import sleep bp = ByPy() x = Browser(driver_name='chrome') url = "https://openapi.baidu.com/oauth/2.0/authorize?client_id=q8WE4EpCsau1oS0MplgMKNBn&response_type=code&redirect_uri=oob&scope=basic+netdisk" x.visit(url) username = '******' password = '******' x.fill("userName", username) x.fill('password', password) x.click_link_by_id('TANGRAM_3__submit') test = x.find_by_id('Verifier') print(test) print("\n") bp.mkdir(remotepath='bypy') bp.upload(localpath='d:\\ShareFile\2.jpg', remotepath='bypy', ondup='newcopy') print('上传完毕!')
class Amazon(object): def __init__(self, keyword): self.url = "https://www.amazon.com" self.name = "".join(random.sample(string.ascii_letters + string.digits, 6)) self.email = "".join(random.sample(string.ascii_letters + string.digits, 16)) + "@163.com" self.password = "".join(random.sample(string.ascii_letters + string.digits, 8)) self.keyword = keyword self.chrome_options = Options() logging.basicConfig(filename='amazon.log', level=logging.DEBUG) self.conn = pymysql.connect(host='192.168.0.211', port=6033, user='******', password='******', db='amazon') self.cs = self.conn.cursor() self.cs.execute('select id,ip,port from register_proxy_ips where is_alived = 1 order by id desc limit 1') self.proxy_ip = self.cs.fetchone() self.cs.execute('update register_proxy_ips set is_alived = 0 where id = %s' % self.proxy_ip[0]) self.conn.commit() logging.debug(self.proxy_ip) # self.chrome_options.add_argument('--proxy-server=http://{host}:{port}'.format(host=self.proxy_ip[1], port=self.proxy_ip[2])) self.browser = Browser('chrome', user_agent=generate_user_agent(device_type='desktop')) def run(self): self.acess() self.search_kw() i = 1 while i < 7: ad_list = self.browser.find_by_xpath('//li[contains(@class, "AdHolder")]') if ad_list: ad_list[0].find_by_tag('h2').click() break else: time.sleep(300) self.search_kw() i += 1 if i > 6: self.browser.quit() self.register() self.add_pay_method() self.add_address() self.buy_goods() self.add_list() def acess(self): self.browser.visit(self.url) logging.error("代理IP失效,请求不成功") def search_kw(self): self.browser.find_by_xpath('//input[@id="twotabsearchtextbox"]').first.fill(self.keyword) self.browser.find_by_xpath('//input[@value="Go"]').click() draggble = self.browser.find_by_xpath('//*[@id="searchTemplate"]') target = self.browser.find_by_xpath('//*[@id="footer"]') draggble.drag_and_drop(target) # time.sleep(random.randint(1, 6)) def register(self): self.browser.find_by_xpath('//*[@id="nav-link-accountList"]').click() self.browser.find_by_xpath('//*[@id="createAccountSubmit"]').click() self.browser.find_by_xpath('//input[@id="ap_customer_name"]').first.fill(self.name) self.browser.find_by_xpath('//input[@id="ap_email"]').first.fill(self.email) self.browser.find_by_xpath('//input[@id="ap_password"]').first.fill(self.password) self.browser.find_by_xpath('//input[@id="ap_password_check"]').first.fill(self.password) self.browser.find_by_xpath('//input[@class="a-button-input"]').click() def add_pay_method(self): self.browser.find_by_xpath('//*[@id="nav-link-accountList"]').click() self.browser.find_by_xpath('//*[@id="a-page"]/div[3]/div/div[2]/div[2]/a/div').click() self.browser.fill('ppw-accountHolderName', paras['card_name']) self.browser.fill('addCreditCardNumber', paras['card_num']) self.browser.execute_script('document.getElementsByName("ppw-expirationDate_month")[0].style.display="block"') self.browser.execute_script('document.getElementsByName("ppw-expirationDate_year")[0].style.display="block"') self.browser.find_by_text('04').click() self.browser.find_by_text('2019').click() self.browser.find_by_name('ppw-widgetEvent:AddCreditCardEvent').click() def add_address(self): self.browser.fill('ppw-fullName', paras['fullname']) self.browser.fill('ppw-line1', paras['line']) self.browser.fill('ppw-city', paras['city']) self.browser.fill('ppw-stateOrRegion', paras['stateOrRegion']) self.browser.fill('ppw-postalCode', paras['postalCode']) self.browser.fill('ppw-phoneNumber', paras['phoneNumber']) self.browser.find_by_name('ppw-widgetEvent:AddAddressEvent').click() def buy_goods(self): self.browser.find_by_xpath('//*[@id="nav-recently-viewed"]').click() self.browser.find_by_xpath('//*[@id="asin_list"]/div[1]/div/a/div[1]/span/div').click() try: self.browser.find_by_xpath('//*[@id="add-to-cart-button"]').click() # add cart self.browser.find_by_xpath('//*[@id="smartShelfAddToCartNative"]').click() except Exception as e: logging.error(e) try: time.sleep(5) self.browser.is_element_present_by_xpath('//i[@class="a-icon a-icon-close"]', wait_time=30) self.browser.find_by_xpath('//i[@class="a-icon a-icon-close"]').click() except Exception: pass try: self.browser.find_by_xpath('//a[@id="hlb-view-cart-announce"]').click() # enter cart except Exception: pass self.browser.execute_script('document.getElementsByName("quantity")[0].style.display="block"') self.browser.find_by_value('10').click() self.browser.find_by_name('quantityBox').clear() self.browser.fill('quantityBox', 999) self.browser.find_by_xpath('//span[@id="a-autoid-1"]').click() self.browser.find_by_xpath('//div[@class="sc-proceed-to-checkout"]').click() self.browser.find_by_xpath('//*[@id="address-book-entry-0"]/div[2]/span/a').click() self.browser.find_by_xpath('//*[@id="shippingOptionFormId"]/div[3]/div/div/span[1]').click() self.browser.find_by_xpath('//*[@id="order-summary-container"]/div/div/div').click() try: self.browser.find_by_xpath('//a[contains(@class, "prime-nothanks-button")]').click() except Exception: pass self.browser.find_by_xpath('//span[contains(@class, "place-order-button-link")]').click() def add_list(self): self.browser.find_by_xpath('//*[@id="nav-recently-viewed"]').click() self.browser.find_by_xpath('//*[@id="asin_list"]/div[1]/div/a/div[1]/span/div').click() self.browser.find_by_xpath('//input[@title="Add to List"]').click() if self.browser.is_element_present_by_text('Add to your list', wait_time=10): self.browser.find_by_xpath('//*[@id="WLHUC_result"]/form/div[2]/span[3]/span').click() self.browser.find_by_xpath('//i[@class="a-icon a-icon-close"]').click() time.sleep(2) self.browser.quit()
print len(file_list) for item in file_list: file_name = item.find_by_tag('td').first.text print file_name, '++++++++++++++++++' item.find_by_tag('td').first.click() file_path = os.path.join(browser_save_path, file_name) time.sleep(1) if os.path.exists(file_path): shutil.move(file_path, save_path) else: print file_name b.quit() if __name__ == '__main__': # browser_save_path = 'C:/Users/wt/Downloads' # base_path = 'D:/work/barra/' # login_url = 'https://fileservice.msci.com/' # base_url = 'https://fileservice.msci.com/m/home/hcqlztti/barra/' # path_list = ['cne5/', '/cne5/model_receipt/', '/cne5/daily/', '/bime/'] # download_by_website(login_url, path_list, base_url, browser_save_path, base_path) # shutil.rmtree('D:/work/download/') # shutil.move(browser_save_path, 'D:/work/barra/cne5/') b = Browser(driver_name='chrome') b.visit('https://vpn-guest.citicsinfo.com') b.fill('svpn_name', 'bj-dongsanhuan-1') b.fill('svpn_password', 'EQJtqXC2') b.find_by_text(u'登 录').click() time.sleep(2) b.find_by_id('sendSms').click()
- Choice the "delete option" and confirm delete in the next page - Get the info from the operation This example will works perfectly if you completed the second part of the django tutorial: https://docs.djangoproject.com/en/dev/intro/tutorial02/ For more information, just check: https://docs.djangoproject.com/en/dev/intro/tutorial01/ NOTE: This was tested when the version of the tutorial was for Django 1.3 """ from splinter.browser import Browser browser = Browser() # You may change this url to the current url from your Poll App browser.visit('http://127.0.0.1:8000/admin/') # You may change the username and password too browser.fill('username', 'douglas') browser.fill('password', '123456') # do login browser.find_by_css('.submit-row input').first.click() # add a new poll browser.find_link_by_href('polls/poll/add/').first.click() browser.fill('question', 'Does this test is completed successfully?') # if you follow the instructions from the tutorial, this is will show # the datetime options from the poll browser.find_by_css('.collapse-toggle').first.click() datetime_fields = browser.find_by_css('.datetimeshortcuts') datetime_fields[0].find_by_tag('a').first.click() datetime_fields[1].find_by_tag('a').first.click() # fill the choices browser.fill('choice_set-0-choice', 'Yup!')
from splinter.browser import Browser #from time import sleep b = Browser('firefox') b.visit('http://www.baidu.com') #b.fill('wd', 'test\r') #b.fill('wd', 'test\n') #b.fill('wd', 'test\r\n') b.fill('wd', 'test') #b.execute_script('document.getElementsByName("f")[0].submit()') script = ''' var e = document.createEvent('KeyboardEvent'); e.initKeyEvent('keypress', true, true, window, false, false, false, false, 13, 0); document.getElementsByName('wd')[0].dispatchEvent(e); ''' b.execute_script(script) #sleep(5) b.type('wd', ' python') #b.type('wd', ' python', slowly=True) # slowly not working
import time from PIL import ImageGrab ''' 使用splinter操作网页 ''' if __name__ =='__main__': # browser=Browser('chrome', headless=True) browser=Browser('chrome') browser.visit("http://wx.zhinengxiyifang.cn/admin/index.html#!/franchiseeManager") # button_1 = browser.find_by_id('su') time.sleep(5) browser.find_by_id('J_Quick2Static').click() browser.fill('TPL_username','linguoyang2008') browser.fill('TPL_password','123456wolf') browser.find_by_id('J_SubmitStatic').click() time.sleep(5) if browser.is_text_present('知乎'): print("找到你了") # browser.driver.close() # 获取当前所有窗口handle列表,这个文档里面有 # 列表里面的窗口按打开顺序排列
#!usr/bin/python from splinter.browser import Browser import re import time br=Browser() br.visit("http://www.160by2.com/Index") br.fill('username','YOUR_PHONE_NUMBER_USED_TO_CREATE_160BY2_ACCOUNT') br.fill('password','YOUR_ACCOUNT_PASSWORD') button = br.find_by_name("") button.click() stringurl=br.url stringurl2=stringurl.split("id=",1)[1] id=stringurl2.split("id=",1)[1] jsstring="window.parent.openPage('SendSMS?id="+id+"', 'aSendSMS', 'aSMS', 'ulSMS')" br.execute_script(jsstring) time.sleep(8) br.execute_script(jsstring) print "JS Executed" time.sleep(8) with br.get_iframe('by2Frame') as iframe: iframe.fill("sendSMSMsg","Well, I guess robot's do send SMSes when spandan wants them to ;)") iframe.find_by_tag("input")[10].fill("THE_PHONE_NUMBER_YOU_WANT_TO_SEND_SMS_TO") button2=iframe.find_by_id("btnsendsms").first print button2.value button2.click()
# -*- coding: utf-8 -*- """ Created on Wed Jul 29 02:27:11 2015 @author: bam8 """ # tasks for tomorrow # just start with one traders profile, doesn't matter who # and extract data from main page such as last seen and rank # then go into transactions page and get all of them from splinter.browser import Browser browser = Browser() browser.visit('http://google.com') browser.fill('q', 'splinter - python acceptance testing for web applications') button = browser.find_by_css('.lsb').first button.first.click() if browser.is_text_present('http://splinter.cobrateam.info'): print "Yes, found it! :)" else: print "No, didn't find it :(" browser.quit()
# -*- coding:utf-8 -*- from splinter.browser import Browser b = Browser(driver_name="chrome") url = "https://kyfw.12306.cn/otn/leftTicket/init" b.visit(url) b.find_by_text(u"登录").click() b.fill("loginUserDTO.user_name","qianyu668899") b.fill("userDTO.password","qsjy81zwxy") b.cookies.all() b.cookies.add({"_jc_save_fromStation":u"上海"}) b.cookies.add({"_jc_save_fromDate":"2016-02-01"}) b.cookies.add({u'_jc_save_toStation':u'南昌'}) b.cookies.all() b.reload() b.find_by_text(u"查询").click()
class TestCase(ptc.PloneTestCase): def __init__(self): self.browser = Browser(driver_name='firefox') self.host, self.port = startZServer() def afterSetUp(self): self.browser.visit('http://%s:%s/plone' % (self.host, self.port)) def beforeTearDown(self): self.browser.quit() def portal_visit(self, url): self.browser.visit('http://%s:%s/plone/%s' % (self.host, self.port, url)) def portal_home(self): self.browser.visit('http://%s:%s/plone/' % (self.host, self.port)) def portal_login(self, user, password): self.portal_visit('login_form') self.browser.fill('__ac_name', user) self.browser.fill('__ac_password', password) self.browser.find_by_name('submit').first.click() def portal_login_as_owner(self): self.portal_login(user=portal_owner, password=default_password) def portal_logout(self): self.portal_visit('logout') def portal_search(self, search_word): self.browser.fill('SearchableText','%s' % (search_word)) self.browser.find_by_css('.searchButton').first.click() def portal_navigate_submenu(self, option): self.browser.find_by_xpath("//li[contains(@id, 'contentview')]/a[text()='%s']" % (option)).first.click() def portal_click_a_personaltool(self, personaltool): self.browser.click_link_by_href('http://%s:%s/plone/dashboard' % (self.host, self.port)) self.browser.click_link_by_text('%s' % (personaltool)) def portal_add_user(self, fullname, username, email, password): self.portal_click_a_personaltool('Site Setup') self.browser.click_link_by_text('Users and Groups') self.browser.find_by_name('form.button.AddUser').first.click() self.browser.fill('form.fullname','%s' % (fullname)) self.browser.fill('form.username','%s' % (username)) self.browser.fill('form.email','%s' % (email)) self.browser.fill('form.password','%s' % (password)) self.browser.fill('form.password_ctl','%s' % (password)) self.browser.find_by_id('form.actions.register').first.click() def portal_add_user_as_manager(self, fullname, username, email, password): self.portal_click_a_personaltool('Site Setup') self.browser.click_link_by_text('Users and Groups') self.browser.find_by_name('form.button.AddUser').first.click() self.browser.fill('form.fullname','%s' % (fullname)) self.browser.fill('form.username','%s' % (username)) self.browser.fill('form.email','%s' % (email)) self.browser.fill('form.password','%s' % (password)) self.browser.fill('form.password_ctl','%s' % (password)) self.browser.find_by_id('form.groups.0').first.click() self.browser.find_by_id('form.actions.register').first.click() def portal_change_user_role(self, username, new_role): self.portal_click_a_personaltool('Site Setup') self.browser.click_link_by_text('Users and Groups') self.browser.find_by_xpath("//tr[*/input[@value='%s']]//input[@value='%s']" % (username, new_role)).first.click() self.browser.find_by_name('form.button.Modify').first.click() def portal_click_enable_content_types(self): self.browser.find_by_css('a[title="Add new items inside this item"]').first.click() def portal_add_content_type(self, type): self.portal_click_enable_content_types() self.browser.click_link_by_text('%s' % (type)) def portal_click_content_item_action(self): self.browser.find_by_css('a[title="Actions for the current content item"]').first.click() def portal_add_item_action(self, type): self.portal_click_content_item_action() self.browser.click_link_by_text('%s' % (type)) def portal_list_states(self): self.browser.find_by_css('a[title="Change the state of this item"]').first.click() def portal_modify_state_to(self, state): self.portal_list_states() self.browser.click_link_by_text('%s' % (state))