def qianpiao(): global b b = Browser(driver_name="chrome") b.visit(login_url) login() b.visit(zhangxueyou_url) ul = b.find_by_name(u"2017[A CLASSIC TOUR学友.经典] 世界巡回演唱会—扬州站") print(len(ul)) for i in range(index,len(ul)): ul[i].check() if ul[i]['class'] != 'on': sleep(0.5) b.find_by_xpath(u'//*[@id="JqueBoxer"]/div[1]/a').click() else: break if login_url in b.url: login() b.find_by_xpath(u'//*[@id="JreltList"]/ul/li[3]/dl/input').fill(ticket_num) b.find_by_xpath(u"/html/body/div[12]/div[2]/div[3]/div[5]/a").click() b.find_by_xpath(u"//*[@id='zidTabs']/li[2]").check() b.find_by_xpath(u'//*[@id="payNew-conts-show"]/div[2]/ul/li[2]/input').click() while pay_oreder not in b.url: b.find_by_id(u'saveOrder').click()
def downloadCSV( geneName ): ## import webdriver from splinter.browser import Browser ## alternative driver api ## driver = webdriver.Chrome("C:/Users/Jeff/Downloads/chromedriver.exe") ## import the driver, and visit the exac.broadinstitute.org webpage ## b = driver.get("http://exac.broadinstitute.org/awesome?query=SAMD11") ## load chrome driver, visit targer url b = Browser(driver_name="chrome") url = "http://exac.broadinstitute.org/awesome?query=" + geneName b.visit(url) ## find the LoF button, by web elementary inspect button = b.find_by_id(u"consequence_lof_variant_button") ## trigger the button button.click() ## find the Export to CSV button, also by web elementary inspect button2 = b.find_by_id(u"export_to_csv") ## trigger the button, download the target CSV document button2.click() b.quit()
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 huoche(): global b b = Browser(driver_name="chrome") b.visit(ticket_url) while b.is_text_present(u"登录"): sleep(1) login() if b.url == initmy_url: break try: print u"购票页面..." # 跳回购票页面 b.visit(ticket_url) # 加载查询信息 b.cookies.add({"_jc_save_fromStation": starts}) b.cookies.add({"_jc_save_toStation": ends}) b.cookies.add({"_jc_save_fromDate": dtime}) b.reload() sleep(2) count = 0 # 循环点击预订 if order != 0: while b.url == ticket_url: b.find_by_text(u"查询").click() count +=1 print u"循环点击查询... 第 %s 次" % count sleep(1) try: b.find_by_text(u"预订")[order - 1].click() except: print u"还没开始预订" continue else: while b.url == ticket_url: b.find_by_text(u"查询").click() count += 1 print u"循环点击查询... 第 %s 次" % count sleep(1) try: for i in b.find_by_text(u"预订"): i.click() except: print u"还没开始预订" continue sleep(1) b.find_by_text(pa)[1].click() #b.find_by_text(u"提交订单").click() sleep(1) b.find_by_id('qr_submit_id').click() print u"能做的都做了.....不再对浏览器进行任何操作" except Exception as e: print(traceback.print_exc())
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
class DVTTVedicConverter(object): def __init__(self): # We presume that you've installed chrome driver as per https://splinter.readthedocs.io/en/latest/drivers/chrome.html . self.browser = Browser('chrome', headless=True) self.browser.visit('file://' + os.path.join(os.path.dirname(__file__), "data", 'DV-TTVedicNormal ==_ यूनिकोड परिवर्तित्र.html')) def convert(self, text): input_box = self.browser.find_by_id("legacy_text") convert_button = self.browser.find_by_name("converter") input_box.fill(text) convert_button.click() output_box = self.browser.find_by_id("unicode_text") return output_box.value
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 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 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 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()
class selectCourse(object): #指定浏览器类型 driver_name = 'chrome' executable_path = '' #用户名 密码 username = "" passwd = "" #cookies值自己找 order = 0 """网址""" #4m3登录URL login_url = "https://ids.tongji.edu.cn:8443/nidp/saml2/sso?id=1868&sid=0&option=credential&sid=0" #4m3主页URL initmy_url = "http://4m3.tongji.edu.cn/eams/home.action" #选课页面URL,先手动点击选课页面然后再拷贝过来,不同人选课页面可能不同 elect_url = '' def __init__(self): self.driver_name = 'chrome' self.executable_path = os.getcwd() + '/chromedriver' print("Welcome To Use The Tool") def login(self): self.driver.visit(self.initmy_url) #填充密码 self.driver.fill("Ecom_User_ID", self.username) #sleep(1) self.driver.fill("Ecom_Password", self.passwd) #print("等待验证码,自行输入....") while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(1400, 1000) self.login() #sleep(1) while (True): self.driver.visit(self.initmy_url) self.driver.visit(self.elect_url) #课号,F12自己查 self.driver.find_by_id("").click() #教师课号,F12自己查 self.driver.find_by_id("").click() count = 0 while (True): self.driver.find_by_id("savetable-btn").click() sleep(2) self.driver.find_by_id("cboxClose").click() #选课间隔时间,不建议太短,否则会崩溃 sleep(3) print("已抢%d次" % count)
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('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 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 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 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)
def getInfo(self): self.company = 'Discover' self.bureaus = 'TransUnion' try: browser = Browser(driver_name='firefox') browser.visit(self.url) browser.driver.set_window_size(self.window_size_x, self.window_size_y) browser.find_by_id(self.username_id).fill(self.username) browser.find_by_id(self.password_id).fill(self.password) browser.find_by_id(self.loginbutton_id).click() time.sleep(5) self.score = browser.find_by_css(self.score_class).text.encode('ascii','ignore') self.score = re.sub("[^0-9]", "", self.score) self.scoreDate = browser.find_by_css(self.date_class).text.encode('ascii','ignore') browser.quit() print(self.company + " succeeds!") except: print(self.company + " failed!") pdb.set_trace() if browser: browser.quit()
def login(url, brower_name): """log in""" print "Executing login" browser = Browser(driver_name=brower_name) while datetime.now().second < 50: print datetime.now().second browser.visit(url) button = browser.find_by_id("ContentPlaceHolder1_hlOfferAlertAA") if button: button.click() else: print "not found"
def login(): global b b = Browser(driver_name="chrome") for i in range(0,3): b.visit(gift_url) b.find_by_id("ptLoginBtn").click() sleep(1) with b.get_iframe('loginFrame') as iframe: iframe.find_by_id('u').fill(username[i]) iframe.find_by_id('p').fill(passwd[i]) iframe.find_by_id('go').click() sleep(1) b.find_by_tag("a")[2].click() sleep(1) #大区,需要改成自己的,这是大地飞鹰 b.find_by_xpath('//select[@id="area1ContentId_wuxia"]/option[@value="7609516"]')._element.click() sleep(1) #服务器,需要改成自己的,这是藏锋谷 b.find_by_xpath('//select[@id="areaContentId_wuxia"]/option[@value="2002"]')._element.click() sleep(1) b.find_by_id("confirmButtonId_wuxia").click() sleep(1) b.get_alert().dismiss() sleep(1) b.find_by_id("ptLogoutBtn").click() sleep(5) print u"领取完毕" sleep(3)
def getInfo(self): self.company = 'Citi' self.bureaus = 'Equifax' try: browser = Browser(driver_name='firefox') browser.visit(self.url) browser.driver.set_window_size(self.window_size_x, self.window_size_y) time.sleep(5) browser.find_by_id(self.username_id).fill(self.username) time.sleep(5) browser.find_by_name(self.password_name).fill(self.password) time.sleep(5) browser.find_by_value(self.loginbutton_value).click() time.sleep(10) browser.find_by_id(self.fico_button).click() time.sleep(10) self.score = browser.find_by_id(self.score_id).text.encode('ascii','ignore') self.score = re.sub("[^0-9]", "", self.score) self.scoreDate = browser.find_by_id(self.date_id).text.encode('ascii','ignore') browser.quit() print(self.company + " succeeds!") except: print(self.company + " failed!") pdb.set_trace() if browser: 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 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 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 huo_che(): global b b = Browser(driver_name="chrome") # 选择其他的浏览器需要换其他的webdriver,webdriver需要设置在环境变量 b.visit(ticket_url) while b.is_text_present(u"登录"): sleep(1) login() if b.url == initmy_url: break try: print(u"购票页面...") # 跳回购票页面 b.visit(ticket_url) # 加载查询信息 b.cookies.add({u"_jc_save_fromStation": starts}) b.cookies.add({u"_jc_save_toStation": ends}) b.cookies.add({u"_jc_save_fromDate": d_time}) b.reload() sleep(2) count = 0 # 循环点击预订 if order != 0: while b.url == ticket_url: b.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) sleep(1) # 时间间隔可调,但是12306有反爬系统 try: b.find_by_text(u"预订")[order - 1].click() break except Exception as e: print(e) continue else: while b.url == ticket_url: b.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) sleep(1) try: for i in b.find_by_text(u"预订"): i.click() except Exception as e: print(e) continue b.find_by_id(u"normalPassenger_0").click() # 这个是选择常用联系人,0代表选的常用联系人列表的第一个乘客 b.find_by_id(u"submitOrder_id").click() sleep(0.5) b.find_by_id(u"qr_submit_id").click() print(u"自行支付") except Exception as e: print(e) print(traceback.print_exc())
def getInfo(self): self.company = 'American Express' self.bureaus = 'Experian' try: browser = Browser(driver_name='firefox') browser.visit(self.url) browser.driver.set_window_size(self.window_size_x, self.window_size_y) browser.find_by_id(self.username_id).fill(self.username) browser.find_by_id(self.password_id).fill(self.password) browser.find_by_id(self.loginbutton_id).click() time.sleep(1) browser.find_by_id(self.fico_button).click() time.sleep(1) self.score = browser.find_by_id(self.score_id).text.encode('ascii','ignore') self.scoreDate = browser.find_by_id(self.date_id).text.encode('ascii','ignore') self.previous = browser.find_by_id(self.previous_id).text.encode('ascii','ignore') browser.quit() print(self.company + " succeeds!") except: print(self.company + " failed!") if browser: browser.quit()
def splinter(brow,url,id,pwd): browser = Browser(brow) #login 126 email websize browser.visit(url) #wait web element loading time.sleep(5) #fill in account and password browser.find_by_id('idInput').fill(id) browser.find_by_id('pwdInput').fill(pwd) #click the button of login browser.find_by_id('loginBtn').click()
class TemMail(): def __init__(self): 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('https://www.moakt.com') self.driver.find_by_name('random').click() while self.driver.url == 'https://www.moakt.com/zh/mail': return def getMailName(self): sleep(1) self.driver.execute_script('changeAddress();') sleep(1) mailname = self.driver.find_by_id('email-address').text return mailname def getEmail(self): while True: self.driver.find_by_text(u"刷新列表").click() temdata = self.driver.find_by_text(u"激活您的ProcessOn帐号") if len(temdata) == 0: sleep(2) else: em = self.driver.find_by_text(u"激活您的ProcessOn帐号").first url = em["href"] + '/content' self.getEmailDea(url) break def getEmailDea(self, emlurl): self.driver.visit(emlurl) temtext = self.driver.html url_verify = re.findall( r"https://www.processon.com/signup/verification/\w+", temtext) ss_mail = requests.Session() rsp_verify = ss_mail.get(url_verify[0]) if rsp_verify.status_code == 200: self.driver.quit() else: print("failure:" + rsp_verify.status_code)
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 start(url, username, pwd): b = Browser(driver_name="firefox") b.visit(url) login(b, username, pwd) try: b.find_by_id("btn-reservation").click() except AttributeError as e: print('Error:', e) time.sleep(10) while True: loop(b, url) if b.is_element_present_by_id("tryBtn"): b.find_by_id("tryBtn").click() time.sleep(4) elif b.title == u"订单结算页 -京东商城": b.find_by_id("order-submit").click() else: print(u'恭喜你,抢购成功') break
QUANTIDADE_TAMANHOS = len(SELETOR_TAMANHOS) if QUANTIDADE_TAMANHOS == 1: TAMANHO = SELETOR_TAMANHOS.first else: TAMANHO = SELETOR_TAMANHOS[random.randint(0, QUANTIDADE_TAMANHOS-1)] #seleciona tamanho TAMANHO.find_by_css('a')[1].click() #clica na tag A que adiciona itens time.sleep(SLEEP) i = i + 1 #Fechar a modal de quantidade time.sleep(SLEEP) B.find_by_css('button.btn.btn-primary').click()""" #Abrir modal de seleção de cliente time.sleep(SLEEP) B.find_by_id('input-lojista').click() """#Buscar por um cliente específico time.sleep(SLEEP) B.find_by_id('inputModalLojistas').type(PESQUISACLIENTE)""" #Buscar por um cliente aleatório time.sleep(SLEEP) CLIENTE1 = 'Cliente1T' CLIENTE2 = 'Cliente2T' CLIENTE3 = 'Cliente3T' CLIENTES = [CLIENTE1, CLIENTE2, CLIENTE3] CLIENTE = random.choice(CLIENTES) B.find_by_id('inputModalLojistas').type(CLIENTE) #print CLIENTE #Selecionar o cliente que foi buscado
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()
b = Browser(driver_name='chrome') b.visit( "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F" ) time.sleep(5) try: b.find_link_by_href( "https://passport.weibo.cn/signin/other?r=http%3A%2F%2Fm.weibo.cn%2F" ).click() except: print("找不到第三方账号按钮") time.sleep(2) try: b.find_link_by_href( "https://passport.weibo.com/othersitebind/authorize?entry=mweibo&site=qq&res=other&callback=http%3A%2F%2Fm.weibo.cn%2F" ).click() except: print("找不到qq账号登录") time.sleep(4) try: b.find_link_by_href("javascript:void(0);").click() except: print("找不到账号密码登录") time.sleep(2) b.find_by_id("u").fill(username) b.find_by_id("p").fill(password) b.find_by_id("login_button").click()
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('上传完毕!')
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)
# with open("D:\\code\\python\\new\\Brush ticket\\IP.txt",'w') as f: # for i in all_url: # f.write(i) # f.write('\n') # return all_url #转发特定微博 def forwardMoney(b): time.sleep(10) b.visit("https://m.weibo.cn/1255795640/4192089996527286") time.sleep(10) oneForward(b) for i in range(3): username, password = login(i) b = Browser(driver_name='chrome') b.visit( "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F" ) time.sleep(10) b.find_by_id("loginName").fill(username) b.find_by_id("loginPassword").fill(password) b.find_by_id("loginAction").click() time.sleep(10) forward(b) time.sleep(10) b.quit() time.sleep(10)
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()
d.find_by_text('内场1355').click() d.find_by_id('btnBuyNow').click() time.sleep(5) order_confirm(d) def payment(d): if d.title == '选择支付方式': d.find_by_text('支付平台付款').click() d.find_by_value('213').first.click() time.sleep(1) d.find_by_id('submit2').click() else: d.reload() order_confirm(d) payment(d) d = Browser(driver_name='chrome') login(d) time.sleep(5) d.visit(url_ticket) d.find_by_text('内场1355').click() time.sleep(4) d.find_by_id('btnBuyNow').click() order_confirm(d) payment(d) time.sleep(3) if d.title == '支付宝 - 网上支付 安全快速!': print('SUCCESS!') else: print('RETRY PLEASE!')
class huoche(object): driver_name = '' executable_path = '' #用户名,密码 username = u"xxx" passwd = u"xxx" # cookies值得自己去找, 下面两个分别是沈阳, 哈尔滨 starts = u"%u6C88%u9633%2CSYT" ends = u"%u54C8%u5C14%u6EE8%2CHBB" # 时间格式2018-01-19 dtime = u"2018-01-19" # 车次,选择第几趟,0则从上之下依次点击 order = 0 ###乘客名 users = [u"xxx",u"xxx"] ##席位 xb = u"二等座" pz = u"成人票" """网址""" ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" login_url = "https://kyfw.12306.cn/otn/login/init" initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" def __init__(self): self.driver_name = 'chrome' self.executable_path = 'D:/chromedriver' def login(self): self.driver.visit(self.login_url) self.driver.fill("loginUserDTO.user_name", self.username) # sleep(1) self.driver.fill("userDTO.password", self.passwd) print(u"等待验证码,自行输入...") while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver = Browser(driver_name=self.driver_name,executable_path=self.executable_path) self.driver.driver.set_window_size(1400, 1000) self.login() # sleep(1) self.driver.visit(self.ticket_url) try: print(u"购票页面开始...") # sleep(1) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() count = 0 if self.order != 0: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) # sleep(1) try: self.driver.find_by_text(u"预订")[self.order - 1].click() except Exception as e: print(e) print(u"还没开始预订") continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) # sleep(0.8) try: for i in self.driver.find_by_text(u"预订"): i.click() sleep(1) except Exception as e: print(e) print(u"还没开始预订 %s" % count) continue print(u"开始预订...") # sleep(3) # self.driver.reload() sleep(1) print(u'开始选择用户...') for user in self.users: self.driver.find_by_text(user).last.click() print(u"提交订单...") sleep(1) self.driver.find_by_text(self.pz).click() self.driver.find_by_id('').select(self.pz) # sleep(1) self.driver.find_by_text(self.xb).click() sleep(1) self.driver.find_by_id('submitOrder_id').click() print(u"开始选座...") self.driver.find_by_id('1D').last.click() self.driver.find_by_id('1F').last.click() sleep(1.5) print(u"确认选座...") self.driver.find_by_id('qr_submit_id').click() except Exception as e: print(e)
site = 'https://kyfw.12306.cn/otn/' # login site, note http:// is required #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()
class TestEngine(object): __sleep_time = 2 __mouse_over = True __mouse_over_sleep = 1 def __init__(self, browser_name, execute_path=None): if execute_path is None: self.__browser = Browser(browser_name, fullscreen=True) self.__quit = False else: self.__browser = Browser(browser_name, executable_path=execute_path, fullscreen=True) self.__quit = False @staticmethod def set_config(config): TestEngine.__sleep_time = 2 if config.get("sleep_time") is None else config.get("sleep_time") TestEngine.__mouse_over = True if config.get("mouse_over") is None else config.get("mouse_over") TestEngine.__mouse_over_sleep = 1 if config.get("mouse_over_sleep") is None else config.get("mouse_over_sleep") def test_list_acts(self, domain, action_list, back_fun=None, result_back=None): thread_deal = threading.Thread(target=self.__test_list_thread, args=(domain, action_list, back_fun, result_back), name="TestEngine deal tester") thread_deal.start() def test_deal(self, domain, action_obj, back_fun=None, result_back=None): thread_deal = threading.Thread(target=self.__test_do_thread, args=(domain, action_obj, back_fun, result_back), name="TestEngine deal tester") # hasattr(result_back, "__call__") thread_deal.start() def quit(self): self.__quit = True self.__browser.quit() def is_quited(self): return self.__quit def __test_list_thread(self, domain, action_list, back_fun=None, result_back=None): try: for action in action_list: self.__test_do(domain, action, result_back) except Exception as e: raise Exception("[Error code] deal test list failed, error code=", e) finally: if action_list[0].waitClose != 0: sleep(action_list[0].waitClose) if back_fun is None: self.quit() else: back_fun() def __test_do_thread(self, domain, action_obj, back_fun=None, result_back=None): try: self.__test_do(domain, action_obj, result_back) except Exception as e: raise Exception("[Error code] deal test failed, error code=", e) finally: if action_obj.waitClose != 0: sleep(action_obj.waitClose) if back_fun is None: self.quit() else: back_fun() def __test_do(self, domain, action_obj, result_back=None): test_url = domain+action_obj.urlPath self.__browser.visit(test_url) # form表单默认为第一个action循环测试,之后的action按照顺序执行 action_list = TesterActionData().dict_to_list(action_obj.actionList) if action_obj.forms is not None: form_action = action_list[0] if action_list else None forms = TesterForms().dict_to_list(action_obj.forms) for form in forms: params = TesterFormData().dict_to_list(form.params) for param in params: self.__set_value(int(param.formType), param.formElName, param.formElValue.decode("utf-8"), int(param.index)) sleep(TestEngine.__sleep_time) if form_action is not None: self.__deal_action(form_action, result_back) sleep(action_obj.sleepTime) for action_deal in action_list[1:]: self.__deal_action(action_deal, result_back) sleep(action_obj.sleepTime) else: for action_deal in action_list: self.__deal_action(action_deal, result_back) sleep(action_obj.sleepTime) def __set_value(self, form_type, el_name, el_value, index): elements = self.__event_element(form_type, el_name) element = elements[index] if element['type'] in ['text', 'password', 'tel'] or element.tag_name == 'textarea': element.value = el_value elif element['type'] == 'checkbox': if el_value: element.check() else: element.uncheck() elif element['type'] == 'radio': element.click() elif element._element.tag_name == 'select': element.find_by_value(el_value).first._element.click() else: element.value = el_value def __event_element(self, el_type, el_value): ele_type = EL_TYPE.value(el_type) if ele_type == "id": return self.__browser.find_by_id(el_value) elif ele_type == "name": return self.__browser.find_by_name(el_value) elif ele_type == "tag": return self.__browser.find_by_tag(el_value) elif ele_type == "value": return self.__browser.find_by_value(el_value) elif ele_type == "selector": return self.__browser.find_by_xpath(el_value) elif ele_type == "css": return self.__browser.find_by_css(el_value) else: raise ValueError("Test Engine can't deal the element type:%s, el_type:%s", ele_type, el_type) def __deal_action(self, action_data, result_back=None): action_type = ACTION_TYPE.value(action_data.action) # 当页面跳转是抓取最后一个打开的窗口页面 self.__browser.windows.current = self.__browser.windows[-1] if action_type == "click": self.__mouse_of_click(self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)]) elif action_type == "double click": self.__mouse_of_double_click(self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)]) elif action_type == "right click": self.__mouse_of_right_click(self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)]) elif action_type == "mouse over": self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)].mouse_over() elif action_type == "mouse out": self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)].mouse_out() elif action_type == "select": self.__event_element(action_data.elType, action_data.elValue)[int(action_data.index)].select() else: raise Exception("don't find action for action:%s", action_data.action) try: if action_data.testerResult is not None and result_back is not None: sleep(3) result_back(TesterResult(action_data.testerResult, self.__browser.is_text_present(action_data.testerResult))) except Exception: result_back(TesterResult(action_data.testerResult, False)) def __mouse_of_click(self, event_deal_obj): if TestEngine.__mouse_over: event_deal_obj.mouse_over() sleep(TestEngine.__mouse_over_sleep) event_deal_obj.click() else: event_deal_obj.click() def __mouse_of_right_click(self, event_deal_obj): if TestEngine.__mouse_over: event_deal_obj.mouse_over() sleep(TestEngine.__mouse_over_sleep) event_deal_obj.right_click() else: event_deal_obj.click() def __mouse_of_double_click(self, event_deal_obj): if TestEngine.__mouse_over: event_deal_obj.mouse_over() sleep(TestEngine.__mouse_over_sleep) event_deal_obj.double_click() else: event_deal_obj.click()
from splinter.browser import Browser browser = Browser() browser.visit('http://www.office.mikadosoftware.com') browser.click_link_by_href('/login') openidbox = browser.find_by_xpath('''id('column2')/form/p/input[1]''').first openidbox.fill('https://www.google.com/accounts/o8/id') browser.find_by_value('Sign in').first.click() #id="Email" #id="Passwd" browser.find_by_id("Email").first.fill('*****@*****.**') browser.find_by_id("Passwd").first.fill('empathy1') browser.find_by_value('Sign in').first.click() browser.uncheck('remember_choices') browser.find_by_value('Allow').first.click() print browser.title print for z in browser.cookies.driver.get_cookies(): if z['domain'] == u'www.office.mikadosoftware.com' and z['name'] == u'session': print z['value']
#-*- 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()
from splinter.browser import Browser url = raw_input('url:') browser = Browser('firefox') browser.visit(url) if "nike" in url: button = browser.find_by_name("add-to-cart-button") sizeButton = browser.find_by_name("skuAndSize") elif "adidas" in url: button = browser.find_by_id("buyingtools-add-to-cart-button") sizeButton.click(); button.click()
class huoche(object): """docstring for huoche""" driver_name='' executable_path='' #用户名,密码 username="******" passwd ="password" # cookies值得自己去找, 下面两个分别是上海, 太原南 starts = "%u5317%u4EAC%2CBJP" ends = "%u4E34%u6C82%2CLVK" # 时间格式2018-01-19 dtime = "2018-02-12" # 车次,选择第几趟,0则从上之下依次点击 order = 0 ###乘客名 users = ["XXX"] ##席位 xb = "硬座" pz="成人票" """网址""" ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" login_url = "https://kyfw.12306.cn/otn/login/init" initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy="https://kyfw.12306.cn/otn/confirmPassenger/initDc" login_url='https://kyfw.12306.cn/otn/login/init' def __init__(self): self.driver_name='chrome' def login(self): self.driver.visit(self.login_url) self.driver.fill("loginUserDTO.user_name", self.username) # sleep(1) self.driver.fill("userDTO.password", self.passwd) print ("等待验证码,自行输入...") while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver=Browser(driver_name=self.driver_name) self.driver.driver.set_window_size(1400, 1000) self.login() # sleep(1) self.driver.visit(self.ticket_url) try: print ("购票页面开始...") # sleep(1) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() count=0 if self.order!=0: while self.driver.url==self.ticket_url: self.driver.find_by_text("查询").click() count += 1 print("循环点击查询... 第 %s 次" % count) # sleep(1) try: self.driver.find_by_text("预订")[self.order - 1].click() except Exception as e: print(e) print("还没开始预订") continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text("查询").click() count += 1 print("循环点击查询... 第 %s 次" % count) # sleep(0.8) try: for i in self.driver.find_by_text("预订"): i.click() sleep(1) except Exception as e: print(e) print("还没开始预订 %s" % count) continue print("开始预订...") # sleep(3) # self.driver.reload() sleep(1) print('开始选择用户...') for user in self.users: self.driver.find_by_text(user).last.click() print("提交订单...") sleep(1) # self.driver.find_by_text(self.pz).click() # self.driver.find_by_id('').select(self.pz) # # sleep(1) # self.driver.find_by_text(self.xb).click() # sleep(1) self.driver.find_by_id('submitOrder_id').click() # print u"开始选座..." # self.driver.find_by_id('1D').last.click() # self.driver.find_by_id('1F').last.click() sleep(1.5) print("确认选座...") self.driver.find_by_id('qr_submit_id').click() except Exception as e: print(e)
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()
class huoche(object): driver_name = '' executable_path = '' #用户名,密码 username = u"xxx" passwd = u"xxx" # cookies值得自己去找, 下面两个分别是沈阳, 哈尔滨 starts = u"%u6C88%u9633%2CSYT" ends = u"%u54C8%u5C14%u6EE8%2CHBB" # 时间格式2018-01-19 dtime = u"2018-01-19" # 车次,选择第几趟,0则从上之下依次点击 order = 0 ###乘客名 users = [u"xxx", u"xxx"] ##席位 xb = u"二等座" pz = u"成人票" """网址""" ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" login_url = "https://kyfw.12306.cn/otn/login/init" initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" def __init__(self): self.driver_name = 'chrome' self.executable_path = 'D:/chromedriver' def login(self): self.driver.visit(self.login_url) self.driver.fill("loginUserDTO.user_name", self.username) # sleep(1) self.driver.fill("userDTO.password", self.passwd) print(u"等待验证码,自行输入...") while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(1400, 1000) self.login() # sleep(1) self.driver.visit(self.ticket_url) try: print(u"购票页面开始...") # sleep(1) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() count = 0 if self.order != 0: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) # sleep(1) try: self.driver.find_by_text(u"预订")[self.order - 1].click() except Exception as e: print(e) print(u"还没开始预订") continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print(u"循环点击查询... 第 %s 次" % count) # sleep(0.8) try: for i in self.driver.find_by_text(u"预订"): i.click() sleep(1) except Exception as e: print(e) print(u"还没开始预订 %s" % count) continue print(u"开始预订...") # sleep(3) # self.driver.reload() sleep(1) print(u'开始选择用户...') for user in self.users: self.driver.find_by_text(user).last.click() print(u"提交订单...") sleep(1) self.driver.find_by_text(self.pz).click() self.driver.find_by_id('').select(self.pz) # sleep(1) self.driver.find_by_text(self.xb).click() sleep(1) self.driver.find_by_id('submitOrder_id').click() print(u"开始选座...") self.driver.find_by_id('1D').last.click() self.driver.find_by_id('1F').last.click() sleep(1.5) print(u"确认选座...") self.driver.find_by_id('qr_submit_id').click() except Exception as e: print(e)
#!usr/bin/python from splinter.browser import Browser import re import time import sys import os SongName=sys.argv[1] br=Browser('chrome') br.driver.set_window_size(10,10) br.visit("http://www.youtube.com") time.sleep(5) searchbar=br.find_by_id("masthead-search-terms").first.find_by_tag("input")[0] searchbar.fill(SongName) br.execute_script("if (document.getElementById('masthead-search-term').value == '') return false; document.getElementById('masthead-search').submit(); return false;;return true;") URLfirst=br.find_by_id("results").first.find_by_tag("a") YoutubeURL=URLfirst[1]['href'] br.quit() os.system("cd ~/Downloads") executionstring="youtube-dl -x --extract-audio --audio-format mp3 --audio-quality 0 "+YoutubeURL os.system(executionstring) ##For Youtube-mp3.org method, uncomment all the lines below. Since I had ##youtube-dl installed on my laptop, I am using a method which has higher quality, but takes ##more time to install #br.visit("http://www.youtube-mp3.org/") #URLarea=br.find_by_id("youtube-url").fill(YoutubeURL) #button=br.find_by_id("submit") #button.click() #print "Ready to click" #time.sleep(10)
class ticket(object): """docstring for 12306抢票""" driver_name = '' executable_path = '' # 用户名,密码 username = u"153****1009" passwd = u"*******" # 车次,选择第几趟,0则从上之下依次点击 order = 1 ###乘客名 users = [u"XXX"] ##席位 xb = u"硬座" pz = u"成人票" """网址""" ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" login_url = "https://kyfw.12306.cn/otn/login/init" initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" # 需要下载chromedriver def __init__(self): self.driver_name = 'chrome' self.executable_path = 'D:\Chrome Driver\chromedriver' def login(self): self.driver.visit(self.login_url) # 填充密码 self.driver.fill("loginUserDTO.user_name", self.username) # sleep(1) self.driver.fill("userDTO.password", self.passwd) print(u"等待验证码,自行输入...") while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(1900, 1000) self.login() # sleep(1) self.driver.visit(self.ticket_url) try: print(u"购票页面开始...") # sleep(1) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() count = 0 if self.order != 0: while self.driver.url == self.ticket_url: try: self.driver.find_by_text(u"查询").click() except Exception as e: continue count += 1 # 根据td的id获取节点以判断是否有票 id需要手工获取 isTicketElement = self.driver.find_by_id("YW_490000502609") if len(isTicketElement) == 0: print("网络错误") continue print(u"循环查询... 第 %s 次,还是木有票" % count) isTicket = self.driver.find_by_id( "YW_490000502609")._element.text sleep(30) # isTicket = "--" or isTicket = "无" 均是指无相应席位的余票 if isTicket == "无": continue # sleep(1) try: self.driver.find_by_text(u"预订")[self.order - 1].click() continue except Exception as e: print(e) print(u"还没开始预订") continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 isTicket = self.driver.find_by_id("YW_490000502609") print(isTicket) sleep(0.8) try: for i in self.driver.find_by_text(u"预订"): i.click() sleep(1) except Exception as e: print(e) print(u"还没开始预订 %s" % count) continue print(u"开始预订...") # sleep(3) # self.driver.reload() sleep(1) print(u'开始选择用户...') for user in self.users: self.driver.find_by_text(user).last.click() # seatType_1 选择席位 略 print(u"提交订单...") sleep(1) # 选择席别、票种示例 # self.driver.find_by_xpath('//select[@id="seatType_1"]/option[@value="0"]')._element.click() # self.driver.find_by_text(self.pz).click() # self.driver.find_by_id('').select(self.pz) # # sleep(1) # self.driver.find_by_text(self.xb).click() # sleep(1) self.driver.find_by_id('submitOrder_id').click() # print u"开始选座..." # self.driver.find_by_id('1D').last.click() # self.driver.find_by_id('1F').last.click() sleep(1.5) print(u"确认选座...") self.driver.find_by_id('qr_submit_id').click() except Exception as e: print(e)
def splinter_scrape_bf(city, state): """PURPOSE: To """ city = city.lower() state = state.lower() br = Browser() citystate_string = city+'_'+state+'_us/' url = 'http://www.bringfido.com/lodging/city/'+citystate_string br.visit(url) page = 1 npages = len(br.find_by_xpath('//*[@id="results_paging_controls_bottom"]/span')) columns = ['hotel_id', 'hotel_img_url', 'hotel_url', 'hotel_name', 'hotel_address', 'hotel_city', 'hotel_state', 'hotel_rating', 'hotel_latitude', 'hotel_longitude', 'review_count', 'hotel_address', 'business_id', 'review_id', 'user_id', 'username', 'review_title', 'review_text', 'review_rating', 'review_date'] bigdf = pd.DataFrame(columns=columns) while (page == 1 or page < npages): print('*'*70) print('Now on page {}'.format(page)) archive_links = br.find_by_xpath('//*[@id="results_list"]/div') hotel_names = [] text_summaries = [] links = [] biz_ids = [] hotel_img_urls = [] df = pd.DataFrame(columns=columns) texts = [] titles = [] authors = [] ratings = [] hnms = [] hiurls = [] bids = [] lnks = [] for lnk in archive_links: hotel_names.append(lnk.find_by_xpath('div[2]/h1/a').value) text_summaries.append(lnk.text) this_link = lnk.find_by_xpath('div/h1/a')['href'] links.append(this_link) hotel_img_urls.append(lnk.find_by_xpath('div/div[@class="photo_inner"]/a/img')['src']) biz_ids.append(lnk['id'].split('_')[-1]) for hotel_id, link in enumerate(links): print('*'*75) print('Now on {}: {}'.format(hotel_id, link)) print('*'*75) br.visit(link) # hotel_description = br.find_by_xpath('//*[@class="body"]').text # scrape the address details section of the page details = br.find_by_xpath('//*[@class="address"]').text.split('\n') # now get just the address: address = details[0] # and just the city, state, country, and zip code: csczip = details[1] # and just the phone number # phone = details[2] # now separate the city, state, and zip: city, state, zipcode = csczip.strip().split(',') zipcode = zipcode[3:] #Now using correct Xpath we are fetching URL of archives reviews = br.find_by_xpath('//*[@class="review_container"]') print(reviews) print('') for rev in reviews: titles.append(rev.find_by_xpath('div/div[1]').text) authors.append(rev.find_by_xpath('div/div[2]').text) texts.append(rev.find_by_xpath('div/div[3]').text) ratings.append(rev.find_by_xpath('div[2]/img')['src'].split('/')[-1][0:1]) hnms.append(hotel_names[hotel_id]) hiurls.append(hotel_img_urls[hotel_id]) bids.append(biz_ids[hotel_id]) lnks.append(link) print(rev.find_by_xpath('div[2]/img')['src'].split('/')[-1][0:1]) print('Number of new titles: {}'.format(len(titles))) print('Number of new ratings: {}'.format(len(ratings))) df['review_title'] = titles df['username'] = authors df['review_text'] = texts df['review_rating'] = ratings df['hotel_id'] = hotel_id df['hotel_name'] = hnms df['hotel_url'] = lnks df['hotel_img_url'] = hiurls df['hotel_address'] = address df['hotel_city'] = city df['hotel_state'] = state df['hotel_rating'] = np.mean([int(rat) for rat in ratings]) df['hotel_latitude'] = None df['hotel_longitude'] = None df['review_count'] = len(texts) df['review_id'] = 0 df['user_id'] = 0 df['business_id'] = bids print('new entries from this page: {}'.format(len(df))) bigdf = bigdf.append(df.copy()) page += 1 if page < npages: page_timeout = True while page_timeout: br.visit(url) time.sleep(1) print('Now scraping page {} of {}'.format(page, npages)) button = br.find_by_id('page_'+str(page)) print(button) if len(button) > 0: button.click() page_timeout = False bigdf_reviews = bigdf[['hotel_id', 'review_id', 'business_id', 'user_id', 'username', 'review_title', 'review_text', 'review_rating']].copy() bigdf_hotels = bigdf[['hotel_id', 'hotel_url', 'hotel_img_url', 'hotel_name', 'hotel_address', 'hotel_city', 'hotel_state', 'hotel_rating', 'hotel_latitude', 'hotel_longitude', 'business_id', 'review_count']].copy() bigdf_hotels.drop_duplicates(subset='business_id', inplace=True) bigdf_hotels['hotel_id'] = None bigdf_reviews['review_id'] = None print('Number of bf reviews to add: {}'.format(len(bigdf_reviews))) engine = cadb.connect_aws_db(write_unicode=True) bigdf_reviews.to_sql('bf_reviews', engine, if_exists='append', index=False) bigdf_hotels.to_sql('bf_hotels', engine, if_exists='append', index=False)
class BrushTicket(object): """买票类及实现方法""" def __init__(self, passengers_number): """定义实例属性,初始化""" cp = ConfigParser() cp.read("conf/city.conf", encoding='UTF-8') sections = cp.sections() city = sections[0] key_list = cp.options(city) self.city_dict = {} for key in key_list: self.city_dict[key] = cp.get(city, key) cp = ConfigParser() cp.read("conf/12306.conf", encoding='UTF-8') sections = cp.sections() pessenger = sections[passengers_number] # 乘客姓名 self.passengers = cp.get(pessenger, 'name') # 起始站和终点站 self.from_station = self.city_dict[cp.get(pessenger, 'from_station')] self.to_station = self.city_dict[cp.get(pessenger, 'to_station')] # 乘车日期 self.from_time = cp.get(pessenger, 'from_time') # 车次编号 self.number = cp.get(pessenger, 'coach_number') seat_type = cp.get(pessenger, 'seat_type') # 座位类型所在td位置 if seat_type == '商务座特等座': seat_type_index = 1 seat_type_value = 9 elif seat_type == '一等座': seat_type_index = 2 seat_type_value = 'M' elif seat_type == '二等座': seat_type_index = 3 seat_type_value = 0 elif seat_type == '高级软卧': seat_type_index = 4 seat_type_value = 6 elif seat_type == '软卧': seat_type_index = 5 seat_type_value = 4 elif seat_type == '动卧': seat_type_index = 6 seat_type_value = 'F' elif seat_type == '硬卧': seat_type_index = 7 seat_type_value = 3 elif seat_type == '软座': seat_type_index = 8 seat_type_value = 2 elif seat_type == '硬座': seat_type_index = 9 seat_type_value = 1 elif seat_type == '无座': seat_type_index = 10 seat_type_value = 1 elif seat_type == '其他': seat_type_index = 11 seat_type_value = 1 else: seat_type_index = 7 seat_type_value = 3 self.seat_type_index = seat_type_index self.seat_type_value = seat_type_value # 通知信息 # self.receiver_mobile = receiver_mobile self.receiver_email = cp.get(pessenger, 'email') # 新版12306官网主要页面网址 self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html' self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html' self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc' # 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloads self.driver_name = 'chrome' self.driver = Browser(driver_name=self.driver_name) def do_login(self): """登录功能实现,识别验证码 可以使用12306APP 扫一扫登录""" self.driver.visit(self.login_url) sleep(1) # 选择登陆方式登陆 print('请扫码登陆或者账号登陆……') while True: if self.driver.url != self.init_my_url: sleep(1) else: break def start_brush(self): """买票功能实现""" # 浏览器窗口最大化 self.driver.driver.maximize_window() # 登陆 self.do_login() # 跳转到抢票页面 self.driver.visit(self.ticket_url) try: print('开始刷票……') title_start = '开始抢票' # self.send_mail(self.receiver_email, '开始抢票' + self.from_time + # '的车票,请关注邮箱抢票通知', title_start) # 加载车票查询信息 self.driver.cookies.add( {"_jc_save_fromStation": self.from_station}) self.driver.cookies.add({"_jc_save_toStation": self.to_station}) self.driver.cookies.add({"_jc_save_fromDate": self.from_time}) self.driver.reload() count = 0 while self.driver.url == self.ticket_url: self.driver.find_by_text('查询').click() sleep(1) count += 1 print('第%d次点击查询……' % count) try: current_tr = self.driver.find_by_xpath( '//tr[@datatran="' + self.number + '"]/preceding-sibling::tr[1]') if current_tr: if current_tr.find_by_tag('td')[ self.seat_type_index].text == '--': print('无此座位类型出售,已结束当前刷票,请重新开启!') sys.exit(1) elif current_tr.find_by_tag('td')[ self.seat_type_index].text == '无': print('无票,继续尝试……') sleep(1) else: # 有票,尝试预订 print('刷到票了(余票数:' + str( current_tr.find_by_tag('td')[ self.seat_type_index].text) + '),开始尝试预订……') current_tr.find_by_css('td.no-br>a')[0].click() sleep(1) key_value = 1 for p in self.passengers: # 选择用户 print('开始选择用户……') self.driver.find_by_text(p).last.click() # 选择座位类型 print('开始选择席别……') if self.seat_type_value != 0: self.driver.find_by_xpath( "//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click() key_value += 1 sleep(0.2) if p[-1] == ')': self.driver.find_by_id( 'dialog_xsertcj_ok').click() print('正在提交订单……') self.driver.find_by_id('submitOrder_id').click() sleep(2) # 查看放回结果是否正常 submit_false_info = self.driver.find_by_id( 'orderResultInfo_id')[0].text if submit_false_info != '': print(submit_false_info) self.driver.find_by_id( 'qr_closeTranforDialog_id').click() sleep(0.2) self.driver.find_by_id('preStep_id').click() sleep(0.3) continue print('正在确认订单……') self.driver.find_by_id('qr_submit_id').click() print('预订成功,请及时前往支付……') # 发送通知信息 title = '抢票票成功!!' self.send_mail( self.receiver_email, '恭喜您,抢到了' + self.from_time + '的车票,请及时前往12306支付订单!', title) else: print('不存在当前车次【%s】,已结束当前刷票,请重新开启!' % self.number) sys.exit(1) except Exception as error_info: print(error_info) except Exception as error_info: print(error_info) def send_mail(self, receiver_address, content, title): mail_host = 'smtp.163.com' # 163用户名 mail_user = '******' # 密码(部分邮箱为授权码) mail_pass = '******' # 邮件发送方邮箱地址 sender = '*****@*****.**' # 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 receivers_list = ['*****@*****.**', receiver_address] email = Email(mail_host, mail_user, mail_pass) for receiver in receivers_list: # 设置email信息 # 邮件内容设置 smtpObj = email.getConnection() message = MIMEText(str(content), 'plain', 'utf-8') # 邮件主题 message['Subject'] = title # 发送方信息 message['From'] = sender # 接受方信息 message['To'] = receiver email.send_email(smtpObj, sender, receiver, message)
from splinter.browser import Browser 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列表,这个文档里面有 # 列表里面的窗口按打开顺序排列
def getInfo(self): self.company = 'Barclay' self.bureaus = 'TransUnion' try: browser = Browser(driver_name='firefox') browser.visit(self.url) browser.driver.set_window_size(self.window_size_x, self.window_size_y) browser.find_by_id(self.username_id).fill(self.username) browser.find_by_id(self.continue_button).click() time.sleep(5) browser.find_by_id(self.password_id).fill(self.password) browser.find_by_id(self.loginbutton_id).click() time.sleep(5) digit1 = browser.find_by_id('digit1')['class'] digit2 = browser.find_by_id('digit2')['class'] digit3 = browser.find_by_id('digit3')['class'] self.score = digit1 + digit2 + digit3 self.score = re.sub("[^0-9]", "", self.score) self.scoreDate = browser.find_by_id(self.date_id).text.encode('ascii','ignore') self.scoreDate = "last updated on " + re.sub("[^0-9/]", "", self.scoreDate) browser.quit() print(self.company + " succeeds!") except: print(self.company + " failed!") if browser: browser.quit()
class huoche(object): """docstring for huoche""" driver_name = '' executable_path = '' #用户名,密码 username = u"12306用户名" passwd = u"12306密码" # cookies值得自己去找, 下面两个分别是上海, 太原南 starts = u"%u4E0A%u6D77%2CSHH" ends = u"%u592A%u539F%2CTYV" # 时间格式2018-01-19 dtime = u"2018-01-19" # 车次,选择第几趟,0则从上之下依次点击 order = 0 ###乘客名 users = [u"你的名字"] ##席位 xb = u"二等座" pz = u"成人票" """ 网址 """ """ 12306查询URL """ ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init" """ 12306登录URL """ login_url = "https://kyfw.12306.cn/otn/login/init" """ 我的12306 """ initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306" """ 购票确认URL """ buy = "https://kyfw.12306.cn/otn/confirmPassenger/initDc" def __init__(self): self.driver_name = 'chrome' self.executable_path = '/usr/local/bin/chromedriver' def login(self): self.driver.visit(self.login_url) # 填充密码 self.driver.fill("loginUserDTO.user_name", self.username) # sleep(1) self.driver.fill("userDTO.password", self.passwd) print u"等待验证码,自行输入..." while True: if self.driver.url != self.initmy_url: sleep(1) else: break def start(self): self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(1400, 1000) self.login() # sleep(1) self.driver.visit(self.ticket_url) try: print u"购票页面开始..." # sleep(1) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() count = 0 if self.order != 0: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print u"循环点击查询... 第 %s 次" % count # sleep(1) try: self.driver.find_by_text(u"预订")[self.order - 1].click() except Exception as e: print e print u"还没开始预订" continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text(u"查询").click() count += 1 print u"循环点击查询... 第 %s 次" % count # sleep(0.8) try: for i in self.driver.find_by_text(u"预订"): i.click() sleep(1) except Exception as e: print e print u"还没开始预订 %s" % count continue print u"开始预订..." # sleep(3) # self.driver.reload() sleep(1) print u'开始选择用户...' for user in self.users: self.driver.find_by_text(user).last.click() print u"提交订单..." sleep(1) # self.driver.find_by_text(self.pz).click() # self.driver.find_by_id('').select(self.pz) # # sleep(1) # self.driver.find_by_text(self.xb).click() # sleep(1) self.driver.find_by_id('submitOrder_id').click() # print u"开始选座..." # self.driver.find_by_id('1D').last.click() # self.driver.find_by_id('1F').last.click() sleep(1.5) print u"确认选座..." self.driver.find_by_id('qr_submit_id').click() except Exception as e: print e
def huoche(): ends = "%u5357%u660C%2CNCG" global b b = Browser(driver_name="chrome") # b = Browser() b.visit(ticket_url) # b.execute_script('alert("开始刷票喽~~~~")') # sleep(2) # b.get_alert().dismiss() while b.is_text_present(u"登录"): sleep(1) login() if b.url == initmy_url: break try: #跳回购票页面 b.visit(ticket_url) #加载查询信息 b.cookies.add({"_jc_save_fromStation":starts}) b.cookies.add({"_jc_save_toStation":ends}) b.cookies.add({"_jc_save_fromDate":starttime}) b.cookies.add({"_jc_save_toDate":endtime}) b.reload() i = 1 b.find_by_name(ttype)[4].click() stations = b.find_by_name(fromStation) if stations: stations[0].click() else: print "no stations can select" #循环点击预订 if order != 0: while b.url == ticket_url: print "execute loop order != 0" b.find_by_text(u"查询").click() if b.find_by_text(u"预订"): sleep(0.3) b.find_by_text(u"预订")[order - 1].click() print b.url if b.is_text_present(u"证件号码",wait_time=0.2): # print [ i.text for i in b.find_by_text(pa) ] b.find_by_id("normalPassenger_0").click() b.find_by_id("normalPassenger_1").click() else: # b.execute_script('alert("似乎没有可预订选项")') # b.get_alert().dismiss() print "似乎没有可预订选项" pass else: while b.url == ticket_url: print "execute loop order == 0" b.find_by_text(u"查询").click() if b.find_by_text(u"预订"): sleep(0.3) for i in b.find_by_text(u"预订"): i.click() sleep(0.1) if b.is_text_present(u"证件号码"): # b.find_by_text(pa)[1].click() b.find_by_id("normalPassenger_0").click() b.find_by_id("normalPassenger_1").click() # b.find_by_text("李芷嫣")[0].click() else: # b.execute_script('alert("似乎没有可预订选项")') # b.get_alert().dismiss() print u"似乎没有可预订选项" pass else: print "can't find orderitem" # b.execute_script('alert("能做的都做了")') # b.get_alert().dismiss() print u"能做的都做了.....不再对浏览器进行任何操作" except Exception as e: print u"出错了....%s"%e
# Copyright (c) Rice University 2012-13 # This software is subject to # the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. ### from splinter.browser import Browser browser = Browser() browser.visit("http://www.office.mikadosoftware.com") browser.click_link_by_href("/login") openidbox = browser.find_by_xpath("""id('column2')/form/p/input[1]""").first openidbox.fill("https://www.google.com/accounts/o8/id") browser.find_by_value("Sign in").first.click() # id="Email" # id="Passwd" browser.find_by_id("Email").first.fill("*****@*****.**") browser.find_by_id("Passwd").first.fill("empathy1") browser.find_by_value("Sign in").first.click() browser.uncheck("remember_choices") browser.find_by_value("Allow").first.click() print browser.title print for z in browser.cookies.driver.get_cookies(): if z["domain"] == u"www.office.mikadosoftware.com" and z["name"] == u"session": print z["value"]
class Buy_Tickets(object): # 初始化 def __init__(self, username, passwd, order, passengers, dtime, starts, ends): self.url_template = ( 'https://kyfw.12306.cn/otn/leftTicket/query{}?leftTicketDTO.' 'train_date={}&' 'leftTicketDTO.from_station={}&' 'leftTicketDTO.to_station={}&' 'purpose_codes=ADULT' ) self.username = username self.passwd = passwd # 日期 self.dtime = dtime # 乘客名 self.passengers = passengers.split(',') # 起始地和终点 self.starts = Station_Parse.parse_station().parse(starts) self.ends = Station_Parse.parse_station().parse(ends) if self.starts is None or self.ends is None: self.title = '提示' self.message = '请输入有效的车站名' messagebox.showinfo(self.title, self.message) # 车次 self.order = order if self.order != '0': self.order = self.order_transfer() while(not self.order): sleep(1) self.order = self.order_transfer() # 起始地和终点转为cookie值 self.starts = self.Get_Cookies()[0] + '%2C' + self.starts self.ends = self.Get_Cookies()[1] + '%2C' + self.ends self.login_url = 'https://kyfw.12306.cn/otn/login/init' self.initMy_url = 'https://kyfw.12306.cn/otn/index/initMy12306' self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init' self.driver_name = 'chrome' self.executable_path = 'D:\\Python35\\Scripts\\chromedriver.exe' # 登录 def login(self): self.driver.visit(self.login_url) self.driver.fill('loginUserDTO.user_name', self.username) self.driver.fill('userDTO.password', self.passwd) self.title = '提示' self.message = '请在自动打开的浏览器中输入验证码!' messagebox.showinfo(self.title, self.message) while True: if self.driver.url != self.initMy_url: sleep(1) else: break # 车次转换 def order_transfer(self): self.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3294.6 Safari/537.36'} self.res = requests.get(self.url_template.format('A', self.dtime, self.starts, self.ends), headers=self.headers, verify=False) try: try: self.trains = self.res.json()['data']['result'] except: self.res = requests.get(self.url_template.format('Z', self.dtime, self.starts, self.ends), headers=self.headers, verify=False) self.trains = self.res.json()['data']['result'] self.num = 0 for self.train in self.trains: self.data_list = self.train.split('|') if self.data_list[3] == self.order: break self.num += 1 if self.num == len(self.trains): self.title = '提示' self.message = '您输入的车次不存在,系统将自动选择任意车次!' messagebox.showinfo(self.title, self.message) self.num = '0' return self.num except: title = '提示' message = '因为网络原因正在重新尝试!' messagebox.showinfo(title, message) return None # 中文转Unicode def to_unicode(self, string): self.uni = '' for s in string: self.uni += hex(ord(s)).upper().replace('0X', '%u') return self.uni # 将起始地和终点转化为相应的Cookies def Get_Cookies(self): return [self.to_unicode(self.starts), self.to_unicode(self.ends)] # 买票 def start_buy(self): self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path) self.driver.driver.set_window_size(700, 500) self.login() self.driver.visit(self.ticket_url) try: self.title = '提示' self.message = '开始购票!' messagebox.showinfo(self.title, self.message) # 加载查询信息 self.driver.cookies.add({"_jc_save_fromStation": self.starts}) self.driver.cookies.add({"_jc_save_toStation": self.ends}) self.driver.cookies.add({"_jc_save_fromDate": self.dtime}) self.driver.reload() if self.order != '0': while self.driver.url == self.ticket_url: self.driver.find_by_text('查询').click() # self.title = '提示' # self.message = '开始尝试预订...' # messagebox.showinfo(self.title, self.message) try: self.driver.find_by_text('预订')[self.order].click() sleep(1.5) except: # self.title = '提示' # self.message = '预订失败...' # messagebox.showinfo(self.title, self.message) continue else: while self.driver.url == self.ticket_url: self.driver.find_by_text('查询').click() # self.title = '提示' # self.message = '开始尝试预订...' # messagebox.showinfo(self.title, self.message) try: for i in self.driver.find_by_text('预订'): i.click() sleep(1) except: # self.title = '提示' # self.message = '预订失败...' # messagebox.showinfo(self.title, self.message) continue self.title = '提示' self.message = '开始选择用户~~~' messagebox.showinfo(self.title, self.message) sleep(1) for p in self.passengers: self.driver.find_by_text(p).last.click() sleep(0.5) if p[-1] == ')': self.driver.find_by_id('dialog_xsertcj_ok').click() self.title = '提示' self.message = '提交订单中...' messagebox.showinfo(self.title, self.message) sleep(1) self.driver.find_by_id('submitOrder_id').click() sleep(2) self.title = '提示' self.message = '确认选座中...' messagebox.showinfo(self.title, self.message) self.driver.find_by_id('qr_submit_id').click() self.title = '提示' self.message = '预订成功...' messagebox.showinfo(self.title, self.message) self.content = '恭喜您抢票成功,请在半小时内完成支付!!!' _ = os.system('mshta vbscript:createobject("sapi.spvoice").speak("%s")(window.close)' % self.content) except: self.title = '提示' self.message = '出现了一点小错误,可能是输入信息有误导致的...' messagebox.showinfo(self.title, self.message)
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))
class BrushTicket(object): """买票类及实现方法""" def __init__(self, passengers, from_time, from_station, to_station, numbers, seat_type, receiver_mobile, receiver_email): """定义实例属性,初始化""" # 乘客姓名 self.passengers = passengers # 起始站和终点站 self.from_station = from_station self.to_station = to_station # 车次 self.numbers = list(map(lambda number: number.capitalize(), numbers)) # 乘车日期 self.from_time = from_time # 座位类型所在td位置 if seat_type == '商务座特等座': seat_type_index = 1 seat_type_value = 9 elif seat_type == '一等座': seat_type_index = 2 seat_type_value = 'M' elif seat_type == '二等座': seat_type_index = 3 seat_type_value = 0 elif seat_type == '高级软卧': seat_type_index = 4 seat_type_value = 6 elif seat_type == '软卧': seat_type_index = 5 seat_type_value = 4 elif seat_type == '动卧': seat_type_index = 6 seat_type_value = 'F' elif seat_type == '硬卧': seat_type_index = 7 seat_type_value = 3 elif seat_type == '软座': seat_type_index = 8 seat_type_value = 2 elif seat_type == '硬座': seat_type_index = 9 seat_type_value = 1 elif seat_type == '无座': seat_type_index = 10 seat_type_value = 1 elif seat_type == '其他': seat_type_index = 11 seat_type_value = 1 else: seat_type_index = 7 seat_type_value = 3 self.seat_type_index = seat_type_index self.seat_type_value = seat_type_value # 通知信息 self.receiver_mobile = receiver_mobile self.receiver_email = receiver_email # 新版12306官网主要页面网址 self.login_url = 'https://kyfw.12306.cn/otn/resources/login.html' self.init_my_url = 'https://kyfw.12306.cn/otn/view/index.html' self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc' # 浏览器驱动信息,驱动下载页:https://sites.google.com/a/chromium.org/chromedriver/downloads self.driver_name = 'chrome' self.driver = Browser(driver_name=self.driver_name) def do_login(self): """登录功能实现,手动识别验证码进行登录""" self.driver.visit(self.login_url) sleep(1) # 选择登陆方式登陆 print('请扫码登陆或者账号登陆……') while True: if self.driver.url != self.init_my_url: sleep(1) else: break def start_brush(self): """买票功能实现""" # 浏览器窗口最大化 self.driver.driver.maximize_window() # 登陆 self.do_login() # 跳转到抢票页面 self.driver.visit(self.ticket_url) sleep(1) try: print('开始刷票……') # 加载车票查询信息 self.driver.cookies.add( {"_jc_save_fromStation": self.from_station}) self.driver.cookies.add({"_jc_save_toStation": self.to_station}) self.driver.cookies.add({"_jc_save_fromDate": self.from_time}) self.driver.reload() count = 0 while self.driver.url == self.ticket_url: self.driver.find_by_text('查询').click() sleep(1) count += 1 print('第%d次点击查询……' % count) try: start_list = self.driver.find_by_css('.start-t') for start_time in start_list: current_time = start_time.text current_tr = start_time.find_by_xpath('ancestor::tr') if current_tr: car_no = current_tr.find_by_css('.number').text if car_no in self.numbers: if current_tr.find_by_tag('td')[ self.seat_type_index].text == '--': print( '%s无此座位类型出售,继续……' % (car_no + '(' + current_time + ')', )) sleep(0.2) elif current_tr.find_by_tag('td')[ self.seat_type_index].text == '无': print( '%s无票,继续尝试……' % (car_no + '(' + current_time + ')', )) sleep(0.2) else: # 有票,尝试预订 print(car_no + '(' + current_time + ')刷到票了(余票数:' + str( current_tr.find_by_tag('td')[ self.seat_type_index].text) + '),开始尝试预订……') current_tr.find_by_css( 'td.no-br>a')[0].click() sleep(1) key_value = 1 for p in self.passengers: if '()' in p: p = p[:-1] + '学生' + p[-1:] # 选择用户 print('开始选择用户……') self.driver.find_by_text( p).last.click() # 选择座位类型 print('开始选择席别……') if self.seat_type_value != 0: self.driver.find_by_xpath( "//select[@id='seatType_" + str(key_value) + "']/option[@value='" + str(self.seat_type_value) + "']").first.click() key_value += 1 sleep(0.2) if p[-1] == ')': self.driver.find_by_id( 'dialog_xsertcj_ok').click() print('正在提交订单……') self.driver.find_by_id( 'submitOrder_id').click() sleep(2) # 查看放回结果是否正常 submit_false_info = self.driver.find_by_id( 'orderResultInfo_id')[0].text if submit_false_info != '': print(submit_false_info) self.driver.find_by_id( 'qr_closeTranforDialog_id').click( ) sleep(0.2) self.driver.find_by_id( 'preStep_id').click() sleep(0.3) continue print('正在确认订单……') self.driver.find_by_id( 'qr_submit_id').click() print('预订成功,请及时前往支付……') # 发送通知信息 self.send_mail(self.receiver_email, '恭喜您,抢到票了,请及时前往12306支付订单!') self.send_sms( self.receiver_mobile, '您的验证码是:8888。请不要把验证码泄露给其他人。') sys.exit(0) else: print('当前车次异常') except Exception as error_info: print(error_info) except Exception as error_info: print(error_info) def send_sms(self, mobile, sms_info): """发送手机通知短信,用的是-互亿无线-的测试短信""" host = "106.ihuyi.com" sms_send_uri = "/webservice/sms.php?method=Submit" account = "C59782899" pass_word = "19d4d9c0796532c7328e8b82e2812655" params = parse.urlencode({ 'account': account, 'password': pass_word, 'content': sms_info, 'mobile': mobile, 'format': 'json' }) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30) conn.request("POST", sms_send_uri, params, headers) response = conn.getresponse() response_str = response.read() conn.close() return response_str def send_mail(self, receiver_address, content): """发送邮件通知""" # 连接邮箱服务器信息 host = 'smtp.163.com' port = 25 sender = '*****@*****.**' # 你的发件邮箱号码 pwd = 'FatBoy666' # 不是登陆密码,是客户端授权密码 # 发件信息 receiver = receiver_address body = '<h2>温馨提醒:</h2><p>' + content + '</p>' msg = MIMEText(body, 'html', _charset="utf-8") msg['subject'] = '抢票成功通知!' msg['from'] = sender msg['to'] = receiver s = smtplib.SMTP(host, port) # 开始登陆邮箱,并发送邮件 s.login(sender, pwd) s.sendmail(sender, receiver, msg.as_string())
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()