def login(self): from splinter import Browser browser = Browser('chrome') browser.visit('https://www.pornhubpremium.com/premium/login') browser.find_by_id('username').first.fill(self.username) browser.find_by_id('password').first.fill(self.password) # browser.find_by_id('remember_me').first.fill('on') browser.check('remember_me') sleep(0.1) # Time in seconds browser.find_by_id('submitLogin').first.click() tries = 0 while browser.url != 'https://www.pornhubpremium.com/': if tries > 10: raise RuntimeError('We can not reach the homepage') sleep(1) # Time in seconds tries += 1 return browser
def xfinity(browser=None): if not browser: print ("Making browser...") browser = Browser('phantomjs') print ("Trying google.com...") browser.visit('http://google.com/') if 'google.' in browser.url: print ("google.com connected :)") return print ("Sign up...") browser.click_link_by_partial_text('Sign up') print ("Filling form...") browser.select("rateplanid", "spn") browser.check('spn_terms') browser.fill('spn_postal', '12345') browser.fill('spn_email', '*****@*****.**') print ("Submitting...") sleep(3) # it did not work without the sleeps browser.find_by_css('.startSessionButton').type(' \n') sleep(7) browser.ensure_success_response() print (browser.screenshot())
class AutoElectBrowser(object): def __init__( self, username, password, course_code, which_class, elect_type='qx', course_type='bx', browser_type='chrome', delay=1, ): self.username = username self.password = password self.course_code = course_code self.which_class = which_class self.elect_type = elect_type self.course_type = course_type self.delay = delay self.browser = Browser(browser_type) self.class_info = [] print(type(self.browser)) def login(self): u"""手动输入验证码后登录,调用该函数将返回抢选界面(必修课选课)的browser对象""" self.browser.visit(website["login"]) self.browser.fill('user', self.username) self.browser.fill('pass', self.password) while self.browser.title != u'上海交通大学教学信息服务网-学生服务平台': time.sleep(0.1) print(self.browser.windows[0], self.browser.windows[1]) self.browser.windows[1].close() def elect_site(self): u"""从教学信息服务网主页面到选课页面""" self.browser.visit(website[self.elect_type]) self.browser.check('CheckBox1') self.browser.find_by_name('btnContinue').first.click() def jump_to_list(self): u"""从某种课程的列表跳转到指定种类的列表 course_type:'bx'必修,'rw'人文,'sk'社科,'zk'自科,'sx'数学与逻辑,'xx'限选,'rx'任选""" self.browser.visit(website[self.course_type]) try: if self.course_type == 'xx': self.browser.choose('gridModule$ctl02$radioButton', 'radioButton') if self.course_type == 'rw': self.browser.choose('gridGModule$ctl02$radioButton', 'radioButton') if self.course_type == 'sk': self.browser.choose('gridGModule$ctl03$radioButton', 'radioButton') if self.course_type == 'zk': self.browser.choose('gridGModule$ctl04$radioButton', 'radioButton') if self.course_type == 'sx': self.browser.choose('gridGModule$ctl05$radioButton', 'radioButton') if self.course_type == 'rx': pass except ValueError as e: print e def course_arrange(self): u"""从课程列表进入到选择教师列表""" browser = self.browser course_code = self.course_code while 1: try: browser.choose('myradiogroup', course_code) time.sleep(self.delay) # 0.6会出现刷新过于频繁 browser.find_by_value(u'课程安排').first.click() if browser.title == 'messagePage': browser.find_by_value(u'返回').first.click() print( u'-------刷新过于频繁' + time.strftime( '%H:%M:%S', time.localtime(time.time())) + '-------') time.sleep(1.2) else: break except StaleElementReferenceException as e: print(e) time.sleep(1) except WebDriverException as e: print(e) time.sleep(1) def check_is_empty(self): u"""若有多个班同时人数未满,将选择列表中第一个,并返回0 若所有班人数满,将返回-1""" browser = self.browser html = browser.html self.class_info = [] soup = BeautifulSoup(html) table = soup.find_all('table', class_='alltab')[0].table all_class = table.contents[1] all_class = all_class.contents[1:-1] for c in all_class: each_class_info = [] each_class = c.contents[1:-1] each_class_info.append( each_class[0].contents[1].contents[0].attrs['value']) each_class = each_class[1:] for ec in each_class: each_class_info.append(unicode(ec.string).strip()) self.class_info.append(each_class_info) for wc in self.which_class: if wc == each_class_info[3]: if each_class_info[11] == u'人数未满': self.browser.choose("myradiogroup", each_class_info[0]) return 0 return -1 def submit(self): self.press_button(u'选定此教师') self.press_button(u'选课提交') def return_page(self): self.press_button(u'返 回') def press_button(self, name): self.browser.find_by_value(name).first.click()
class InstagramWebBot(object): '''Instagram Web Bot for automatic things using web browser.''' LOGIN_URL = 'http://instagram.com/accounts/login/'; MANAGE_CLIENTS_URL = 'http://instagram.com/developer/clients/manage/' REGISTER_CLIENT_URL = 'http://instagram.com/developer/clients/register/' REGISTER_DEVELOPER_URL = 'http://instagram.com/developer/register/' LOGOUT_URL = 'http://instagram.com/accounts/logout/' CHANGE_PASSWORD_URL = 'http://instagram.com/accounts/password/change/' APP_REDIRECT_URI = 'http://lovematically.com/complete/instagram' APP_NAME_CHOICES = ['LOVE', 'AMOR', 'AMORE', 'AMOUR'] WAIT_TIME = 5 is_logged_in = False is_developer = False def __init__(self, username, password, browser=None): if browser is not None: self.browser = browser self.browser.visit(self.LOGOUT_URL) else: self.browser = Browser('firefox', user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36") self.username = username self.password = password def slugify(self, str): return re.sub(r'\W+','_',str).lower() def login(self): '''Creates a login session''' self.browser.visit(self.LOGIN_URL) self.browser.fill('username', self.username) self.browser.fill('password', self.password) btn = self.browser.find_by_value('Log in').first btn.click() if self.browser.title == 'Instagram': self.is_logged_in = True logger.info('Logged in as %s' % self.username) else: self.is_logged_in = False logger.error('Login Failed for %s' % self.username) def change_password(self): self.browser.visit(self.CHANGE_PASSWORD_URL) new_password = random_string_generator(8) self.browser.fill('old_password', self.password) self.browser.fill('new_password1', new_password) self.browser.fill('new_password2', new_password) btn = self.browser.find_by_value('Change Password').first btn.click() if self.browser.is_text_present('Thanks! You have successfully changed your password.'): logger.info('Password Changed') logger.info(new_password) return new_password else: return None def register_developer(self, website="", phone_number="", description=""): ''' Registers the user for developer access in instagram ''' result = {} if not self.is_logged_in: logger.error('Must be logged-in to create register as a developer.') return result; self.browser.visit(self.MANAGE_CLIENTS_URL) if self.browser.is_text_present('Developer Signup'): logger.info('Registering as developer') self.browser.fill('website', website) self.browser.fill('phone_number', phone_number) self.browser.fill('description', description) self.browser.check('accept_terms') btn = self.browser.find_by_value('Sign up').first btn.click() self.register_developer(website, phone_number, description) elif self.browser.is_text_present('Register a New Client'): logger.info('Developer registration done') self.is_developer = True else: logger.info('Developer registration failed') self.is_developer = False return result def create_api_client(self, app_name, description, website_url, redirect_uri): '''Creates a new api client. TODO: 1. Add more error handling cases. ''' result = {} if not self.is_logged_in: logger.error('Must be logged-in to create a api client.') return result; self.browser.visit(self.REGISTER_CLIENT_URL) if self.browser.is_text_present('Too many clients'): logger.error('Client limit exceeded for %s' % self.username) return result; self.browser.fill('name', app_name) self.browser.fill('description', description) self.browser.fill('website_url', website_url) self.browser.fill('redirect_uri', redirect_uri) btn = self.browser.find_by_value('Register').first btn.click() client_card = self.browser.find_by_css('.card.client tbody').first rows = client_card.find_by_tag('tr') for row in rows: key = self.slugify(row.find_by_tag('th').first.text) value = row.find_by_tag('td').first.text result.update({key: value}) return result def fill_api_client_form(self): if not self.is_logged_in: logger.error('Must be logged-in to create a api client.') else: app_name = self.APP_NAME_CHOICES[random.randint(0, (len(self.APP_NAME_CHOICES)-1))] description = random_string_generator() website_url = 'http://'+random_string_generator() redirect_uri = self.APP_REDIRECT_URI self.browser.visit(self.REGISTER_CLIENT_URL) self.browser.fill('name', app_name) self.browser.fill('description', description) self.browser.fill('website_url', website_url) self.browser.fill('redirect_uri', redirect_uri) def shell_fill_api_client_form(self, LOCAL_FILE_URL = "captcha.png"): if not self.is_logged_in: logger.error('Must be logged-in to create a api client.') return False else: self.browser.visit(self.REGISTER_CLIENT_URL) if self.browser.is_text_present('Register new Client ID', wait_time=self.WAIT_TIME): app_name = self.APP_NAME_CHOICES[random.randint(0, (len(self.APP_NAME_CHOICES)-1))] description = random_string_generator() website_url = 'http://'+random_string_generator() redirect_uri = self.APP_REDIRECT_URI self.browser.fill('name', app_name) self.browser.fill('description', description) self.browser.fill('website_url', website_url) self.browser.fill('redirect_uri', redirect_uri) captcha_url = self.browser.find_by_id('recaptcha_challenge_image').first['src'] print captcha_url urllib.urlretrieve(captcha_url, LOCAL_FILE_URL) captcha_input = raw_input('Please enter captcha to continue:') self.browser.find_by_id('recaptcha_response_field').first.fill(captcha_input) btn = self.browser.find_by_value('Register').first btn.click() if self.browser.is_text_present('Invalid captcha', wait_time=self.WAIT_TIME): logger.error('Incorrect CAPTCHA, try again') return self.shell_fill_api_client_form(LOCAL_FILE_URL) elif self.browser.is_text_present('Successfully registered', wait_time=self.WAIT_TIME): logger.info('Client registration successful') return True else: logger.error('Client registration failed: UNKNOW ERROR') return False else: logger.error('Cannot register more clients with this accounts.') return False def get_api_clients(self): self.browser.visit(self.MANAGE_CLIENTS_URL) client_cards = self.browser.find_by_css('.card.client') clients = [] for client_card in client_cards: rows = client_card.find_by_tag('tbody').find_by_tag('tr') name = client_card.find_by_tag('h2').first.text result = {} for row in rows: key = self.slugify(row.find_by_tag('th').first.text) value = row.find_by_tag('td').first.text result.update({key: value}) result.update({'name': name}) clients.append(result) return clients def __del__(self): self.browser.quit()
class Session: def __init__(self, browser, user): self.browser = Browser(browser) self.browser.visit('http://jizdenky.studentagency.cz/') self.browser.fill_form({'passwordAccountCode': user['login'], 'password': user['password']}) self.browser.execute_script('window.scrollTo(0, 100)') button = self.browser.find_by_value('Přihlásit').first button.click() self.user = user self.log = logging.getLogger(__name__) def go_search(self): self.browser.visit('http://jizdenky.studentagency.cz/') def search(self, task, date_return=None, is_open=False): self.browser.find_by_id('hp_form_itinerar').first \ .find_by_xpath('div/input[@type="radio"]' )[1 if date_return or is_open else 0].check() for city, i in [(task.from_city, 1), (task.to_city, 2)]: self.browser.find_by_css('input[tabindex="{}"]'.format(i)) \ .first.fill(city) for item in self.browser.find_by_css('.ui-menu-item'): link = item.find_by_tag('a') if link.value.lower() == city.lower(): link.click() break self.browser.fill('departure:dateField', task.date) if date_return: self.browser.fill('returnDeparture:dateField', date_return) if is_open: self.browser.check('returnTicketOpen') self.browser.find_option_by_text('ISIC').first.check() self.browser.find_by_value('Vyhledat').first.click() while self.browser.is_element_not_present_by_css('.left_column', wait_time=1): pass items = self.browser.find_by_css('.left_column') \ .find_by_xpath('div/div/*') connections = [] for item in items: if item.tag_name == 'h2': date_local = item.text.split(' ')[1] elif item.tag_name == 'div' and item.has_class('routeSummary'): assert date_local if date_local != task.date: break connections.append(Connection(item)) return connections def order_time(self, connection): while True: if connection.click(): self.browser dialog = self.browser.find_by_css('[id^=_wicket_window]') if dialog: dialog.first.find_by_tag('button').click() if self.browser.is_element_present_by_id('sumary_lines', wait_time=1): break self.browser.find_by_id('sumary_lines') \ .first.find_by_tag('button') \ .first.click() seats = {} bus = self.browser.find_by_css('.seatsContainer') if bus: for seat in bus.first.find_by_css( '.seatContainer:not([style*=blocked])'): seats[int(seat.find_by_tag('div').first.html[:-1])] = seat else: bus = self.browser.find_by_css('.vehicle') for seat in bus.first.find_by_css('.free, .selected'): seats[int(seat.text[:-1])] = seat return seats def order_seat(self, seat): if not seat.has_class('selected'): seat.click() for fs in self.browser.find_by_css('fieldset.topRoute'): legend = fs.find_by_css('legend') if legend and 'Pojištění' in legend[0].text: for package in fs.find_by_css('.insurancePackageType'): if 'nechci' in package.find_by_tag('label').text: package.find_by_tag('input').click() time.sleep(1) submit = self.browser.find_by_css('[name^=buttonContainer]').first interaction_type = submit.text reserved = 'Rezervovat' in interaction_type if not reserved: submit.click() time.sleep(1) data = (self.user['first'], self.user['last'], self.user['email'], self.user['phone']) for item, value in zip(self.browser.find_by_id('passengerInfo') .first.find_by_tag('input'), data): item.fill(value) submit = self.browser.find_by_css('[name^=buttonContainer]').first interaction_type = submit.text assert 'Rezervovat' in interaction_type agreement = self.browser.find_by_css('[name="bottomComponent:termsAgreementCont:termsAgreementCB"]') if agreement: agreement[0].check() time.sleep(1) submit.click() with open('conf.yaml') as f: conf = yaml.load(f) if 'email' in conf: email = conf['email'] while self.browser.is_element_not_present_by_id('ticketPage', wait_time=1): pass msg = MIMEText(self.browser.find_by_id('ticketPage').first.html, 'html') msg['Subject'] = 'SA reservation' msg['From'] = email['from'] msg['To'] = self.user['email'] username = email['username'] password = email['password'] server = smtplib.SMTP(email['server']) server.starttls() server.login(username, b64decode(password).decode()) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit()
def register_mac_with_xfinity(mac,output, count = 0,time_out = 30): if(count >= 2): return False if count > 0: output.append("Uncertain if successful, trying again") b = Browser('phantomjs') #'phantomjs' #webdriver.PhantomJS() output.append("Browser Launched") success = False try: url = "https://xfinity.nnu.com/xfinitywifi/?client-mac="+mac.lower() socket.setdefaulttimeout(60) b.visit(url) if b.is_text_present("Your complimentary session has expired."): # b.quit() output.append("Mac has already been registered") success = True if(success==False): b.select("rateplanid","spn") # print b.url email = str(random.randrange(10000000,99999999))+'@comcast.com' zip_code = random.randrange(10000,99999) try: b.fill('spn_postal', zip_code) b.fill('spn_email', email) except: pass try: b.check('spn_terms') except: pass url = b.url b.find_by_value('submit').first.click() b.find_by_value('submit').first.click() output.append("Submitting Mac Request, Waiting for result") waitTime = 0 while(b.url == url and waitTime < time_out): #total shit... time.sleep(1) waitTime += 1 if waitTime>0 and waitTime%15 == 0: output.append("Waiting for request to complete ... ["+str(waitTime)+"s]") #TODO validate..... ie did webpage load/etc if(b.is_text_present("Your complimentary session is now active!")): success = True if(waitTime >= time_out and not success): success = register_mac_with_xfinity(mac,output,count=count+1, time_out=time_out) except Exception, err: print err.message print b.url print b.html success = register_mac_with_xfinity(mac, output, count=count+1, time_out=time_out) pass
# Mouse browser.find_by_tag('h1').mouse_over() browser.find_by_tag('h1').mouse_out() browser.find_by_tag('h1').click() browser.find_by_tag('h1').double_click() browser.find_by_tag('h1').right_click() # Mouse drag and drop draggable = browser.find_by_tag('h1') target = browser.find_by_css('.container') draggable.drag_and_drop(target) # Interacting with forms browser.fill('query', 'my name') browser.attach_file('file', '/path/to/file/somefile.jpg') browser.choose('some-radio', 'radio-value') browser.check('some-check') browser.uncheck('some-check') browser.select('uf', 'rj') # screenshot browser.driver.save_screenshot('your_screenshot.png') # 看不太懂 # trigger JavaScript events, like KeyDown or KeyUp, you can use the type method. browser.type('type', 'typing text') ''' If you pass the argument slowly=True to the type method you can interact with the page on every key pressed. Useful for ''' # testing field's auto completion (the browser will wait until next iteration to type the subsequent key). for key in browser.type('type', 'typing slowly', slowly=True): pass # make some assertion here with the key object :)
#!/usr/bin/python import random from splinter import Browser email = str(random.randrange(10000000, 99999999)) + '@comcast.com' zip_code = random.randrange(10000, 99999) url = 'http://captive.apple.com' browser = Browser('firefox') browser.visit(url) browser.click_link_by_text('Sign up') browser.select("rateplanid", "spn") browser.fill('spn_postal', zip_code) browser.fill('spn_email', email) browser.check('spn_terms') browser.find_by_value('submit').first.click() browser.find_by_value('submit').first.click() browser.quit()
warnings.filterwarnings("ignore") #get_ipython().system('which chromedriver') #if you are not sure where your chromedriver is, you can run this code in a jupyter notebook #use this if you are running on a mac or linux computer/machine executable_path = {'executable_path': chrome_driver_path} browser = Browser('chrome', **executable_path, headless=False) #access captcha bypass login page browser.visit(login_url) #login browser.fill('user', username) browser.fill('passwrd', password) browser.check('cookieneverexp') active_web_element = browser.driver.switch_to_active_element() active_web_element.send_keys(Keys.ENTER) def window(page_posts): for post in np.arange(0, len(page_posts)): try: meta = page_posts[post].find('td', class_='poster_info') uid = meta.find('a') uid = str(uid) uid = uid.split('href="')[1].split('u=')[1].split('"')[0] uid = int(uid) #uid is the UID of the poster tme = page_posts[post].find_all('div', class_='smalltext')[1] tme = str(tme)
#!/usr/bin/python from splinter import Browser b = Browser() url = 'http://google.com' b.visit(url) b.click_link_by_text('Sign up') b.select("rateplanid", "spn") b.fill('spn_postal', '11223') b.fill('spn_email', '*****@*****.**') b.check('spn_terms') b.find_by_value('submit').first.click() b.find_by_value('submit').first.click() url = 'http://google.com'
# element = browser.driver.find_element_by_id("imageFile") # pathToImage = os.path.abspath("static/testing/Capture5.JPG") # element.send_keys(pathToImage) # print("Image chosen...") # time.sleep(2) # browser.click_link_by_id('submit') # print("Image submitted for classification...") # time.sleep(2) assert browser.is_text_present('Please log in to access this page.') == True assert browser.is_text_present('Sign In') == True print("=========================================================") print("Running Test Case 2: Sign in to app") browser.fill('username', 'student') browser.fill('password', "1") browser.check('remember_me') browser.find_by_name('submit').first.click() #Test Case 2 print("Running Test Case 3: Visit Activities/Utilities Page") #browser.visit('http://54.191.193.7:5000/') print("Clicking Play Button") time.sleep(2) browser.find_link_by_text('Play').first.click() print("Play button pressed...") time.sleep(2) assert browser.is_text_present('Activities') == True print("=========================================================") #Test Case 3 print("Running Test Case 4: Test Image Upload Pages")
class Session: def __init__(self, browser, user): self.browser = Browser(browser) self.browser.visit('http://jizdenky.studentagency.cz/') self.browser.fill_form({ 'passwordAccountCode': user['login'], 'password': user['password'] }) self.browser.execute_script('window.scrollTo(0, 100)') button = self.browser.find_by_value('Přihlásit').first button.click() self.user = user self.log = logging.getLogger(__name__) def go_search(self): self.browser.visit('http://jizdenky.studentagency.cz/') def search(self, task, date_return=None, is_open=False): self.browser.find_by_id('hp_form_itinerar').first \ .find_by_xpath('div/input[@type="radio"]' )[1 if date_return or is_open else 0].check() for city, i in [(task.from_city, 1), (task.to_city, 2)]: self.browser.find_by_css('input[tabindex="{}"]'.format(i)) \ .first.fill(city) for item in self.browser.find_by_css('.ui-menu-item'): link = item.find_by_tag('a') if link.value.lower() == city.lower(): link.click() break self.browser.fill('departure:dateField', task.date) if date_return: self.browser.fill('returnDeparture:dateField', date_return) if is_open: self.browser.check('returnTicketOpen') self.browser.find_option_by_text('ISIC').first.check() self.browser.find_by_value('Vyhledat').first.click() while self.browser.is_element_not_present_by_css('.left_column', wait_time=1): pass items = self.browser.find_by_css('.left_column') \ .find_by_xpath('div/div/*') connections = [] for item in items: if item.tag_name == 'h2': date_local = item.text.split(' ')[1] elif item.tag_name == 'div' and item.has_class('routeSummary'): assert date_local if date_local != task.date: break connections.append(Connection(item)) return connections def order_time(self, connection): while True: if connection.click(): self.browser dialog = self.browser.find_by_css('[id^=_wicket_window]') if dialog: dialog.first.find_by_tag('button').click() if self.browser.is_element_present_by_id('sumary_lines', wait_time=1): break self.browser.find_by_id('sumary_lines') \ .first.find_by_tag('button') \ .first.click() seats = {} bus = self.browser.find_by_css('.seatsContainer') if bus: for seat in bus.first.find_by_css( '.seatContainer:not([style*=blocked])'): seats[int(seat.find_by_tag('div').first.html[:-1])] = seat else: bus = self.browser.find_by_css('.vehicle') for seat in bus.first.find_by_css('.free, .selected'): seats[int(seat.text[:-1])] = seat return seats def order_seat(self, seat): if not seat.has_class('selected'): seat.click() for fs in self.browser.find_by_css('fieldset.topRoute'): legend = fs.find_by_css('legend') if legend and 'Pojištění' in legend[0].text: for package in fs.find_by_css('.insurancePackageType'): if 'nechci' in package.find_by_tag('label').text: package.find_by_tag('input').click() time.sleep(1) submit = self.browser.find_by_css('[name^=buttonContainer]').first interaction_type = submit.text reserved = 'Rezervovat' in interaction_type if not reserved: submit.click() time.sleep(1) data = (self.user['first'], self.user['last'], self.user['email'], self.user['phone']) for item, value in zip( self.browser.find_by_id('passengerInfo').first.find_by_tag( 'input'), data): item.fill(value) submit = self.browser.find_by_css('[name^=buttonContainer]').first interaction_type = submit.text assert 'Rezervovat' in interaction_type agreement = self.browser.find_by_css( '[name="bottomComponent:termsAgreementCont:termsAgreementCB"]') if agreement: agreement[0].check() time.sleep(1) submit.click() with open('conf.yaml') as f: conf = yaml.load(f) if 'email' in conf: email = conf['email'] while self.browser.is_element_not_present_by_id('ticketPage', wait_time=1): pass msg = MIMEText( self.browser.find_by_id('ticketPage').first.html, 'html') msg['Subject'] = 'SA reservation' msg['From'] = email['from'] msg['To'] = self.user['email'] username = email['username'] password = email['password'] server = smtplib.SMTP(email['server']) server.starttls() server.login(username, b64decode(password).decode()) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit()