class Bot: def __init__(self, email, password): self.driver = Chrome( ChromeDriverManager().install() ) # automatically install chrome driver acc to os default chrome version self.email = email self.password = password def login(self): self.driver.get('https://www.facebook.com/') email = self.driver.find_element_by_id('email').send_keys(self.email) password = self.driver.find_element_by_id('pass').send_keys( self.password, Keys.RETURN) time.sleep(5) def message_to(self, username): self.driver.get(f'https://www.facebook.com/messages/t/{username}') time.sleep( 20) # showing regular TIMEOUT in 5 secs so changed it to 20 secs try: with open('text.txt', 'r') as file: for word in file.readlines(): run = WebDriverWait(self.driver, 20).until( EC.presence_of_element_located( (By.CLASS_NAME, '_1mf'))).send_keys(word, Keys.RETURN) print(word) except TimeoutException: #please check this its always giving TimeOuts errors print("TimeoutException: Something went wrong. Please try again.") def close_browser(self): self.driver.close() def __exit__(self, exc_type, exc_value, traceback): self.close_browser()
def login_get_cookie(): try: print('正在打开浏览器') path = r'--user-data-dir={}'.format(CHROME_OPTIONS_PATH) print(path) option = ChromeOptions() option.add_argument(path) # option.add_argument('--incognito') # option.add_argument('--single-process') driver = Chrome(executable_path=CHROME_DRIVER_PATH, options=option) driver.set_page_load_timeout(10) print('打开登录页面') driver.get(LOGIN_URL) username = driver.find_element_by_id('username') username.send_keys(USERNAME) pwd = driver.find_element_by_id('pwd') pwd.send_keys(PWD) driver.find_element_by_id('login-button').submit() print('登录完成') time.sleep(3) cookies = driver.get_cookies() print('已获取cookies') driver.quit() new_co = {} for item in cookies: new_co[item.get('name')] = item.get('value') print(json.dumps(new_co)) return new_co except Exception as e: print(e) return {}
def init_driver(): username = '******' # 测试环境平台端 url = r'https://cs1.jsbooks.com.cn/customer/#/customer/user/login' password = "******" #云环境 # url = r'http://www.jssz365.com/user/login' # password = '******' driver = Chrome() driver.implicitly_wait(10) driver.get(url=url) driver.maximize_window() driver.find_element_by_id('userName').send_keys(username) driver.find_element_by_id('password').send_keys(password) driver.find_element_by_id('verifyCode').send_keys('1234') driver.find_element_by_class_name('ant-btn').click() time.sleep(1) driver.find_element_by_class_name('ant-btn').click() # driver.execute_script() # driver.find_element_by_xpath().__setattr__() # driver.find_element_by_css_selector() time.sleep(1) yield driver driver.quit()
def get_reddit_api_keys(): pass_chrome_binary() os.environ['webdriver.chrome.driver'] = './chromedriver' driver = Chrome('./chromedriver') # Log in driver.get('https://www.reddit.com/prefs/apps') driver.find_element_by_id("loginUsername").send_keys(USERNAME) driver.find_element_by_id("loginPassword").send_keys(PASSWORD) driver.find_element_by_xpath( "//button[@class='AnimatedForm__submitButton'][@type='submit']" ).submit() # Create dummy app time.sleep(4) driver.refresh() driver.find_element_by_id("create-app-button").click() driver.find_element_by_xpath( "//*[@id='create-app']/table/tbody/tr[1]/td/input").send_keys('test') driver.find_element_by_xpath("//*[@id='app_type_script']").click() driver.find_element_by_xpath( "//*[@id='create-app']/table/tbody/tr[5]/td/textarea").send_keys( 'for DankMemeBot') driver.find_element_by_xpath( "//*[@id='create-app']/table/tbody/tr[7]/td/input").send_keys( 'http://*****:*****@id='create-app']/button").submit() # Regex Oath2 access token and secret key app_details = driver.find_elements_by_id("developed-apps")[-1].text access_token = re.findall('personal use script\\n(.+)\\n', app_details)[-1] secret = re.findall('\\nsecret(.+)\\n', app_details)[-1] return access_token, secret
def __init__(self, driver: webdriver.Chrome): print("") # Find address by id text = driver.find_element_by_id("address").text # If not true, returns error assert "Fjällgatan 32H" in text print(text) # Find zipcode by id text = driver.find_element_by_id("zipCode").text # If not true, returns error assert "981 39 KIRUNA" in text print(text) print("") # Find email by id text = driver.find_element_by_id("email") # Write email href print(text.get_attribute("href")) print("") # Find phone number by id address = driver.find_element_by_id("phoneNumber") # Write mobile href print(address.get_attribute("href"))
def __init__(self, user, passwd, headless=False, implicit_wait=10): """Makes Login on start user: str user passwd : str password headless : True don't start visible window TODO: Only use explicit wait as recommended in SO """ options = ChromeOptions() if headless: options.add_argument("headless") # to hide window in 'background' driver = Chrome(options=options) driver.implicitly_wait(implicit_wait) # seconds driver.get("https://sei.anm.gov.br/") username = driver.find_element_by_id("txtUsuario") password = driver.find_element_by_id("pwdSenha") orgao = driver.find_element_by_id("selOrgao") username.send_keys(user) password.send_keys(passwd) orgao.send_keys("ANM") driver.find_element_by_name("sbmLogin").click() self.driver = driver
def test_segmentation_on_an_image(browser_headed: Chrome): # get the front page of app browser_headed.get(APP_ADDRESS) # create a temporary image folder = make_folder_with_an_image() filename = os.listdir(folder)[0] file_path = os.path.join(folder, filename) # input the temporary image file_input = browser_headed.find_element_by_id("file-input") file_input.send_keys(file_path) # apply segmentation on temporary image apply_button = browser_headed.find_element_by_id("analyze-button") apply_button.click() # test apply button text changes assert apply_button.text == "Segmenting Items..." # wait for segmentation to complete time.sleep(120) # see if result.png was generated result_element = browser_headed.find_element_by_id("image-picked") result_src = result_element.get_attribute("src") assert "/static/result.png" in result_src
def lookup(subject, number): response = requests.head( 'https://www.albany.edu/registrar/schedule-of-classes-spring.php' ).status_code if (response != 200): return "down" opts = Options() opts.headless = True assert opts.headless browser = Chrome(options=opts) browser.get( 'https://www.albany.edu/registrar/schedule-of-classes-spring.php') search_form = browser.find_element_by_id('Course_Subject') search_form.send_keys(subject) search_form = browser.find_element_by_id('Course_Number') search_form.send_keys(number) search_form.submit() results = browser.find_elements_by_tag_name('body') list1 = [] body = "" for i in results: body += i.text newbody = body[21:] list1 = newbody.split("\n") browser.close() return list(list1)
def browser(): global driver, USER, PASS, MESSAGE_NO_PASSWORD, MESSAGE_NO_USER, MESSAGE_NO_CREDENTIALS, MESSAGE_WRONG_CREDENTIALS, user_input, pass_input, submit_button driver = Chrome() # Pro testovaci ucely jsem pouzil Chrome, # na testovacim stroji mam webdrover v PATH, jinak bych mu zadal cestu. # Pro dalsi testovani by se testum predvaly i ostatni drivery jako: # EventFiringWebDriver, FirefoxDriver, HtmlUnitDriver, InternetExplorerDriver, Edge webdriver, # PhantomJSDriver, RemoteWebDriver, SafariDriver, Opera driver, iOS driver, Android driver driver.get(r"https://hdart.cz/hd-admin/") driver.maximize_window() driver.implicitly_wait(10) # mplicity_wait metoda se postara o to, aby se nacetly vsechny prvky na strance # v tomto pripade mam nastaveno 10s, ale doba cekani je takova, nez se vsechny prvny nactou, # 10s je horni limit. Pokud se stranka nacte drive, tak cekani dale nepokracuje # promene pro nasledujici testy # (vetsinou se to nedava do fixtures, ale do externiho confing.json souboru, # ale pro prehlednost jsem to nechal tady) USER = "******" PASS = "******" MESSAGE_NO_PASSWORD = "******" MESSAGE_NO_USER = "******" MESSAGE_NO_CREDENTIALS = "\nNení vyplněna položka Login.\nNení vyplněna položka Heslo." MESSAGE_WRONG_CREDENTIALS = "Zadané přihlašovací údaje nejsou správné." user_input = driver.find_element_by_id('login') pass_input = driver.find_element_by_id('pass') submit_button = driver.find_element_by_class_name('submit.sendButton') yield driver # Iterator vraci objekt browseru driver.close()
def get_customer_authorization_code(customer_username, customer_password): chrome_options = Options() chrome_options.add_argument("--headless") driver = Chrome(options=chrome_options) url = AUTH_URL.format(client_id=client_id, redirect_uri=redirect_uri) # Go to the authorization url, enter username and password and submit driver.get(url) username = driver.find_element_by_id('username') username.send_keys(customer_username) password = driver.find_element_by_id('password') password.send_keys(customer_password) driver.find_element_by_id('signin_button').click() # The first time you authorize, or change the scope of the authorization, there is a 2nd page # where we need to click an "Authorize button". try: auth_button = WebDriverWait(driver, 2).until( EC.element_to_be_clickable((By.ID, "authorize"))) if auth_button: auth_button.click() except: pass uri = driver.current_url # After submitting, the authorization page redirects to your apps `uri` with a query parameter # `code`, which is the customer authorization code used to authentication the customer client. return uri.split("code=")[1]
def test_searching_in_duckduckgo(): # Opening Chrome browser. The path to chromedriver # set automatically by the webdriver-manager library browser = Chrome(executable_path=ChromeDriverManager().install()) # Opening duckduckgo website browser.get('https://duckduckgo.com/') # Finding the search bar search_bar = browser.find_element_by_id('search_form_input_homepage') # Finding the search button (icon finder) search_button = browser.find_element_by_id('search_button_homepage') # Assertions that items are visible to the user assert search_bar.is_displayed() is True assert search_button.is_displayed() is True # Searching for Shiba Inu breed search_bar.send_keys('Shiba Inu') search_button.click() #Checking that any search result has a title "Shiba Inu" list = browser.find_elements_by_css_selector('.result__title') list_of_titles = [] for i in list: list_of_titles.append(i.text)
def goToCreateAccountStudent(): driver = Chrome("chromedriver.exe") driver.get(index_url) driver.find_element_by_id("studentSelection").click() time.sleep(3) driver.find_element_by_id("createAccountButton").click() return driver
class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = Chrome() def tearDown(self): self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): self.browser.get("http://localhost:8000") self.assertIn("To-Do", self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('To-Do', header_text) # 应用邀请他输入一个代办事项 inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item') # 在文本框输入了“Buy peacock feathers” # 伊迪斯的爱好是使用假蝇做鱼饵钓鱼 inputbox.send_keys('Buy peacock feathers') # 按下回车键后页面更新 # 待办事项表格显示了“1:Buy peacock feathers” inputbox.send_keys(Keys.ENTER) time.sleep(1) table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertTrue( any(row.text == "1:Buy peacock feathers" for row in rows)) # 页面显示一个文本框,可以输入其他的待办事项 # 她输入了“User peacock feathers to make a fly” # 伊利斯做事很有调理 self.fail("Finish the test!") # 页面再次更新,她的清单显示了这两个待办事项 [...]
def __init__(self, driver: webdriver.Chrome): print("") # Find title by id titleText = driver.find_element_by_id("titleTextTest").text # If not true, returns error assert "PIZZERIA SANTOS" in titleText print(titleText) # Find title image by id titleImage = driver.find_element_by_id("titleImageTest") # Find title image by style property print(titleImage.value_of_css_property("background-image")) # Find title phone number by id titlePhoneNumber = driver.find_element_by_id("titlePhoneNumberTest").text # If not true, returns error assert "0630-555-555" in titlePhoneNumber print(titlePhoneNumber) # Find title address by id titleAddress = driver.find_element_by_id("titleAddressTest").text # If not true, returns error assert "Fjällgatan 32H" in titleAddress print(titleAddress)
def search_1(a, b, c): ''' :param a: movie name :param b: empty list for future use :param c: empty dict for future use :return: ''' browser = Chrome(options=opts) browser.get('https://duckduckgo.com') search_form = browser.find_element_by_id('search_form_input_homepage') search_form.send_keys(a + ' кинопоиск') search_form.submit() browser.find_element_by_id('r1-0').click() browser.find_element_by_class_name('styles_link__21QPj').click() results = browser.find_elements_by_class_name('gray') for r in results: r = r.text r = r.strip() r = r.lower() if r == '': continue if r in b: continue else: b.append(r) browser.close() c[a] = b return c
def precondition_setup(): dr = Chrome('chromedriver' + os.sep + 'chromedriver.exe') dr.maximize_window() dr.implicitly_wait(20) dr.get( "http://*****:*****@id='nav_tvs']/..") class_tvs = tvs_parentObj.get_attribute("class") #print('class_tvs:' + class_tvs + ",text:" + tvs_parentObj.text) if ('active' != class_tvs): tvs_parentObj.click() time.sleep(2) devices_parentObj = dr.find_element_by_xpath( "//a[@data-table='tabs-devices']/..") class_tvs_tvs = devices_parentObj.get_attribute("class") #print('class_tvs_tvs:' + class_tvs_tvs + ",text:" + devices_parentObj.text) if ('active' != class_tvs_tvs): devices_parentObj.click() time.sleep(2) #dr.find_element_by_xpath("//fieldset/div[2]/div/div/div/div[2]/div[1]/button[@type='button']").click() #dr.find_element_by_xpath("//fieldset/div[2]/div/div/div/div[2]/div[1]/ul/li/a[text()='50']").click() return dr
def get_cookie(): url = 'http://www.pigai.org/' self_user = '******' self_psw = '16733208014' options = ChromeOptions() options.add_argument('--headless') api = Chrome(options=options) # login api.get(url) WebDriverWait(api, 30).until(EC.presence_of_all_elements_located) user = api.find_element_by_id('username').send_keys(self_user) bak = api.find_element_by_id('lg_logo').click() psw = api.find_element_by_id('password').send_keys(self_psw) login_btn = api.find_element_by_id('ulogin').click() cookies_api = api.get_cookies() # 获取cookie cookies = { 'Cookie': '', } cookie_dir = ';'.join\ ([item['name'] + '=' + item['value'] for item in cookies_api]) cookies['Cookie'] = cookie_dir api.quit() return cookies
def t1_verify_form_authentication(self): ''' function to verify the 'Form Authentication' :return: Returns boolean value ''' try: browser = Chrome(self.chrome_path) ins_obj = inspect.currentframe() func_name = inspect.getframeinfo(ins_obj).function ss_file = RESULT + "\\" + func_name + "_" + str( time.time()).split('.')[0] + ".png" browser.get(self.home_page) browser.find_element_by_link_text("Form Authentication").click() html = browser.page_source cred = re.search(r'Enter\s<em>(.*?)<.*and.*<em>(.*?)<.*password', html) user_name = cred.group(1) pass_word = cred.group(2) browser.find_element_by_id("username").send_keys(user_name) browser.find_element_by_id("password").send_keys(pass_word) browser.find_element_by_class_name("radius").click() expected_text = "You logged into a secure area!" if expected_text in browser.page_source: self.logger.info("Login Successful to Form Authentication") browser.save_screenshot(ss_file) browser.close() return True else: self.logger.error("Login to Form Authentication Failed") raise Exception except Exception as err: self.logger.error(err) return False
def login(): if (not accountFileExists()): createFile() account = getAccountValues() usernameStr = account['username'] passwordStr = account['password'] opts = ChromeOptions() opts.add_experimental_option('detach', True) browser = Chrome(executable_path='chromedriver', chrome_options=opts) browser.get('http://192.168.254.254/html/overview.html') loginBtn = browser.find_element_by_id('logout_span') loginBtn.click() username = browser.find_element_by_id('username') username.send_keys(usernameStr) password = browser.find_element_by_id('password') password.send_keys(passwordStr) popLogin = browser.find_element_by_id('pop_login') popLogin.click() #sends a message send_message(browser)
class Test_homePage01(unittest.TestCase): def setUp(self): self.browser=Chrome("C://Users/Debasis/PycharmProjects/ApiSampleProject/browser_server/chromedriver.exe") self.browser.implicitly_wait(20) self.browser.maximize_window() self.browser.get("https://opensource-demo.orangehrmlive.com/index.php/auth/validateCredentials") self.home_page=HomePage(self.browser) def tearDown(self): self.browser.get_screenshot_as_file("C:/Users/Debasis/PycharmProjects/ApiSampleProject/errorScreenshot"+self._testMethodName+"."+"png") self.browser.close() def test_homePage_valid_tc01(self): # self.home_page.wait_for_loginPage() self.home_page.get_user_name().send_keys("Admin") self.home_page.get_user_passwor().send_keys("admin123") self.home_page.get_user_loginButton().click() self.assertTrue(self.browser.title,'OrangeHRM') def test_homePage_logout(self): try: # self.home_page.wait_for_loginPage() self.home_page.get_user_name().send_keys("Admin") self.home_page.get_user_passwor().send_keys("admin123") self.home_page.get_user_loginButton().click() self.assertTrue(self.browser.title, 'OrangeHRM') self.browser.find_element_by_id("welcome").click self.browser.find_element_by_link_text("Logout").click() self.browser.get_screenshot_as_file("C:/Users/Debasis/PycharmProjects/ApiSampleProject/errorScreenshot/logOut.png") print("Logout Successful") except NoSuchElementException as e: print(e)
def downloadSongs(searches): # Chrome Driver setup. driver = Chrome() driver.implicitly_wait(10) # Perform login. (function hidden in tools file) login(driver, loginUrl) driver.find_element_by_id('nav_menu_19_trigger').click() WebDriverWait(driver, 10).until(EC.title_contains('Ignition3')) # Close the popup window which appears. (function hidden in tools file) performAntiBotCounterMeasures(driver) # Click the downloads sorter twice. (function hidden in tools file) sortSongsByMostDownloads(driver) # Perform our search(es) for searchTerms in searches: searchForTrack(driver, searchTerms) songRows = driver.find_elements_by_css_selector('tr.odd, tr.even') empty = driver.find_elements_by_css_selector('td.dataTables_empty') if not empty: # Open the context menu and ctrl+click to download. downloadSong(driver, songRows[0]) # It throws an exception here because then the browser will remain open for some time, allowing you to download the files. raise Exception('Finished. You\'ll have to manually download the files now and move them to the appropriate location.')
class WebDriver: def __init__(self, headless=True): options = Options() options.headless = headless self.driver = Chrome(chrome_options=options) self.in_course = False self.driver.implicitly_wait(5) self.logged_in = False self.courses = {} def login(self, username, password): self.driver.delete_all_cookies() self.driver.get(login_url) username_element = self.driver.find_element_by_id('username') username_element.send_keys(username) passwd_element = self.driver.find_element_by_id('password') passwd_element.send_keys(password) print('Logging in ... ') passwd_element.send_keys(Keys.RETURN) self.logged_in = True print('Succesfully logged in.') raw_courses = self.driver.find_element_by_class_name('coursefakeclass') raw_courses_list = raw_courses.find_elements_by_xpath('li') for raw_course in raw_courses_list: raw_link = raw_course.find_element_by_xpath('a') description = raw_link.text url = raw_link.get_attribute('href') course = Course(description, url) self.courses[course.name] = course print('Succesfully loaded courses.') def enter_course(self, course_name): course = self.courses[course_name] self.driver.get(course.urls['course']) self.in_course = True name = course.department + ' ' + course.crn + '.' + course.section print('Entered course: ' + name + '.') def create_announcement(self, subject, announcement): if self.in_course: self.driver.find_element_by_xpath('//*[@id="nav"]/li/a').click() subject_field = self.driver.find_element_by_xpath( '//*[@id="subject"]') subject_field.send_keys(subject) iframe = self.driver.find_element_by_xpath( '//*[@id="messagetext_ifr"]') self.driver.switch_to.frame(iframe) html_input = self.driver.find_element_by_xpath('html/body') html_input.send_keys(announcement) self.driver.switch_to.default_content() button = self.driver.find_element_by_class_name('submit') button.click() print('Succesfully created and posted announcement.') else: print('You are not in any course. Can`t make the announcement.') def quit(self): self.driver.quit()
def main(): driver = Chrome("./chromedriver") driver.get("https://accounts.google.com/signin/v2/identifier?service=youtube&uilel=3&passive=true&continue=https" "%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Ddesktop%26hl%3Dzh-TW%26next" "%3Dhttps%253A%252F%252Fwww.youtube.com%252F%253Fgl%253DTW%2526tab%253Dw1&hl=zh-TW&ec=65620&flowName" "=GlifWebSignIn&flowEntry=ServiceLogin") driver.find_element_by_id("identifierId").send_keys("djflsdflkl") driver.find_element_by_css_selector("span.RveJvd.snByac").click()
def test_imdb_search(): driver = Chrome( "/Users/andymckerrow/Helio/QAPoint/Python-Selenium-UI-Tests/_drivers/chromedriver" ) driver.get("https://www.imdb.com/") driver.find_element_by_id('navbar-query').send_keys('badlands') driver.find_element_by_css_selector('[class*="magnifyingglass"]').click() assert driver.title == 'Find - IMDb'
def main(): lines = read() USERNAME = lines[0] PASSWORD = lines[1] EVENT = lines[2] opts = Options() opts.add_argument('--no-sandbox') opts.add_argument('--disable-dev-shm-usage') opts.add_argument('--log-level=3') opts.add_argument('--headless') opts.add_argument('--disable-gpu') browser = Chrome(options=opts) browser.get( 'http://info.vit.ac.in/gravitas18/gravitas/gravitas_coordinator_login.asp' ) wait = WebDriverWait(browser, 100) src = browser.page_source myElem = wait.until(EC.visibility_of_element_located((By.ID, 'loginid'))) loginfield = browser.find_element_by_id('loginid') loginfield.send_keys(USERNAME) pwfield = browser.find_element_by_id('logpassword') pwfield.send_keys(PASSWORD) soup = BeautifulSoup(src, 'html.parser') captcha = soup.find_all("input", type='hidden') captcha = str(captcha[0]) captcha = captcha[-9:-3] #print(captcha) cfield = browser.find_element_by_id('captchacode') cfield.send_keys(captcha) loginbtn = browser.find_element_by_name('frmSubmit') loginbtn.click() #print("waiting for page load") #myElem = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'glyphicon glyphicon-menu-down'))) browser.get( 'http://info.vit.ac.in/gravitas18/gravitas/coord_event_participants.asp' ) #http://info.vit.ac.in/gravitas18/gravitas/coord_event_participants.asp #http://info.vit.ac.in/gravitas18/gravitas/coord_event_participant_list.asp myElem = wait.until(EC.visibility_of_element_located((By.NAME, 'form1'))) viewbtn = browser.find_element_by_name('form1') viewbtn.click() src = browser.page_source scrapeRegs(src, EVENT) browser.quit()
def init_browser(): """Initialize browser and sets dropdown menu items""" browser = Chrome(options=opts) browser.get(base_url) select_no_results = Select( browser.find_element_by_id('versenyeredmeny[oldal]')) competitions = Select( browser.find_element_by_id('versenyeredmeny[verseny]')) return browser, select_no_results, competitions
class Game(): def __init__(self, game_url=None): self.name = 'tetris' options = Options() # ヘッドレスモードを有効にする(次の行をコメントアウトすると画面が表示される)。 options.add_argument('--headless') options.add_argument('--no-sandbox') # ChromeのWebDriverオブジェクトを作成する。 self.driver = Chrome(chrome_options=options) # Googleのトップ画面を開く。 self.driver.get(GAME_URL if game_url is None else game_url) self.enable_actions = [Keys.LEFT, Keys.RIGHT, Keys.UP, Keys.DOWN] self.time = time() self.before_state = None def reset(self): self.game_start() return None, None def step(self, action): self.driver.find_element_by_tag_name('body').send_keys(action) block_text = self.driver.find_element_by_class_name('block-text') states = [ int(i) for i in block_text.get_attribute('data-value').split(',') ] reward = int(self.driver.find_element_by_id('point').text) s = np.array(states).reshape(20, 10) under_state = s[-1] if self.before_state is None: self.before_state = copy(under_state) a = self.before_state else: a = np.clip(under_state - self.before_state, 0, 1) self.before_state = copy(under_state) reward += np.sum(a) * 0.5 game_over = self.game_over() if game_over: reward -= 3 self.before_state = None return states, reward, game_over, {} def game_start(self): start_button = self.driver.find_element_by_id('button') start_button.click() def game_over(self): ids = self.driver.find_elements(By.ID, 'game-over') if len(ids) > 0: return True return False
def ee_get_google_auth_session_py(username, password, dirname): """ Get cookies from https://code.earthengine.google.com using Selenium Args: username: gmail username. password: gmail password. dirname: geckodriver path Returns: A session object that contains the necessary cookies for getting pass to gs://earthengine-uploads/ Examples: >>> import os >>> username = '******' >>> password = os.environ['GMAIL_PASSWORD'] >>> dirname = '/home/aybarpc01/.config/earthengine/' >>> session = ee_get_google_auth_session_py(username, password, dirname) """ options = Options() authorization_url = 'https://code.earthengine.google.com/' uname = username passw = password if os.name == 'nt': path_driver = os.path.join(dirname, 'geckodriver.exe') driver = Chrome(executable_path=path_driver, chrome_options=options) elif os.name == 'posix': path_driver = os.path.join(dirname, 'chromedriver') driver = Chrome(executable_path=path_driver, chrome_options=options) driver.get(authorization_url) username = driver.find_element_by_xpath('//*[@id="identifierId"]') username.send_keys(uname) driver.find_element_by_id('identifierNext').click() password = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))) password.send_keys(passw) task_pass = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.XPATH, '//*[@id="passwordNext"]'))) time.sleep(1) task_pass.click() try: element_g = '//*[@id="view_container"]/div/div/div[2]/div/div[1]/div/form/span/section/div/div/div/div/ul/li[1]/div/div[1]/div/div[2]/div[1]' re_confirm = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, element_g))) re_confirm.click() ee_button = '//*[@id="main"]/div[1]/div[1]/div/div[1]/div/div[1]/div/div[2]/div[1]/div[1]/div/div[1]/button' WebDriverWait(driver, 20).until( EC.presence_of_element_located((By.XPATH, ee_button))) except Exception as e: pass cookies = driver.get_cookies() session = requests.Session() for cookie in cookies: session.cookies.set(cookie['name'], cookie['value']) driver.close() return session
def solveCaptcha(d: webdriver.Chrome): if 'Amazon.com' == d.title: try: time.sleep(random.randint(1,3)) captcha = AmazonCaptcha.fromdriver(d).solve() print(captcha + 'doc: ' + d.page_source) d.find_element_by_id('captchacharacters').send_keys(captcha) d.find_element_by_tag_name('button').click() except: l('Unable to pass captcha!!!')
def defter_sor(defter_no, yol, settings): opts = Options() opts.headless = True driver = Chrome(options=opts, executable_path='lib\geckodriver\chromedriver.exe') driver.get('{}'.format(settings[8][2])) no_listesi = defter_no.split("-") defter_parametreleri = settings[25][2] defter_secicileri = settings[26][2] def_par = defter_parametreleri.split("-") def_sec = defter_secicileri.split("-") if def_sec[0] == "0": driver.find_element_by_id(def_par[0]).send_keys(no_listesi[0]) elif def_sec[0] == "1": driver.find_element_by_class_name(def_par[0]).send_keys(no_listesi[0]) elif def_sec[0] == "2": driver.find_element_by_name(def_par[0]).send_keys(no_listesi[0]) else: pass if def_sec[1] == "0": driver.find_element_by_id(def_par[1]).send_keys(no_listesi[1]) elif def_sec[1] == "1": driver.find_element_by_class_name(def_par[1]).send_keys(no_listesi[1]) elif def_sec[1] == "2": driver.find_element_by_name(def_par[1]).send_keys(no_listesi[1]) else: pass if def_sec[2] == "0": driver.find_element_by_id(def_par[2]).send_keys(no_listesi[2]) elif def_sec[2] == "1": driver.find_element_by_class_name(def_par[2]).send_keys(no_listesi[2]) elif def_sec[2] == "2": driver.find_element_by_name(def_par[2]).send_keys(no_listesi[2]) else: pass if def_sec[3] == "0": driver.find_element_by_id(def_par[3]).send_keys(no_listesi[3]) elif def_sec[3] == "1": driver.find_element_by_class_name(def_par[3]).send_keys(no_listesi[3]) elif def_sec[3] == "2": driver.find_element_by_name(def_par[3]).send_keys(no_listesi[3]) else: pass if def_sec[4] == "0": tetikle = driver.find_element_by_id(def_par[4]) elif def_sec[4] == "1": tetikle = driver.find_element_by_class_name(def_par[4]) elif def_sec[4] =="2": tetikle = driver.find_element_by_name(def_par[4]) else: pass tetikle.click() time.sleep(2) path = settings[0][2] + "\\" + yol + "\\defter-sorgu.png" driver.save_screenshot('{}'.format(path)) os.startfile(path) driver.quit()
def extract_citation_for_publication(link): """ this function craws the list of articles from a given link. If it has next page, it will continue to it until there is none @param[in] profile_url the link of google scholar profile you want to crawl @return the list of articles as a list where each entry is dictionary """ browser=Browser('chromedriver.exe') citation={} # go the citation view # as the page is written is javascript, we are not able to get its content via urllib2 # intead we will use Selenium to simulate a web browser to render the page # req=urllib2.Request(publication[k]['link'], headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'}) # p=urllib2.urlopen(req) # sub_soup=BeautifulSoup(p.readlines()[0], 'html.parser') # s=sub_soup.find(id='gs_ccl') browser.get(link) while True: citation_root=browser.find_element_by_id('gs_ccl') citation_list=citation_root.find_elements_by_class_name('gs_r') for citation_item in citation_list: # title title=citation_item.find_element_by_class_name('gs_rt').text # try to get the downloading link, if there is one try: link=citation_item.find_element_by_id('gs_ggsW2') link=link.find_element_by_link_text(link.text).get_attribute('href') except: link=None # author author_line=citation_item.find_element_by_class_name('gs_a') author_name=author_line.text.split(', ') author={} # for each of the author, find its link if its exits for a in author_name: try: print '.', # there is a google scholar profile with author item=author_line.find_element_by_link_text(a) author[a]=item.get_attribute('href') except: # there is not such profile author[a]=None # we can also press the cite button to get the detailed citation information, skipped here citation[title]={'link':link, 'author': author} # go to next page, if there is one if not next_page(browser): break # close browser.close() return citation
conn = cx_Oracle.connect(config_list['dblink_cds_eit100']) cursor = conn.cursor() email = browser.find_element_by_css_selector('input[name="USER"]') email.send_keys(credential['user_name']) password = browser.find_element_by_css_selector('input[name="PASSWORD"]') password.send_keys(credential['password']) logon = browser.find_element_by_css_selector('input.btn.btn-primary') logon.click() browser.get('https://eit1-i.svcs.hp.com/cds/LoadLdssAsync') load_option = browser.find_element_by_id('UploadOptionList') load_option.send_keys('Validate Only') file_selector = browser.find_element_by_id('ldssfile') file_selector.send_keys(path_upload_ldss) upload = browser.find_element_by_css_selector('input[value="Upload"]') upload.click() time.sleep(10) job_tran_run_id = get_job_tran_run_id(browser, tran_name, submitter_input) downloadable_ready(cursor, job_tran_run_id) if downloadable_ready(cursor, job_tran_run_id):
browser.get('https://eit1-i.svcs.hp.com/cds/') # Site-Minder url USER1=input("Please enter the User Name:") PASSWORD1 = getpass.getpass("Password: "******"USER"]') email.send_keys(USER1) password = browser.find_element_by_css_selector('input[name="PASSWORD"]') password.send_keys(PASSWORD1) logon = browser.find_element_by_css_selector('input.btn.btn-primary') logon.click() browser.get('https://eit1-i.svcs.hp.com/cds/LoadLdssAsync') load_option = browser.find_element_by_id('UploadOptionList') load_option.send_keys('Validate Only') file_selector = browser.find_element_by_id('ldssfile') file_selector.send_keys(r'C:\Users\tangjing\Desktop\Auto-Reg\Automation.xlsx') upload = browser.find_element_by_css_selector('input[value="Upload"]') upload.click() console = browser.find_element_by_link_text('CDS Console') console.click() submitter = browser.find_element_by_id('Filters_Submitter') submitter.clear() submitter = browser.find_element_by_id('Filters_Submitter')
def order(shop=None, browser=None, lego_set=None, order_list=None, username=None, password=None): """ Fill in LEGO parts to be ordered in LEGO's customer service shop. """ from selenium.common.exceptions import NoSuchElementException from selenium.webdriver import Chrome, Firefox from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait from time import sleep order_list = order_list.split(',') shop_url = 'https://wwwsecure.us.lego.com/{shop}/service/replacementparts/order'.format(shop=shop) browser = Chrome() if browser == 'chrome' else Firefox() browser.get(shop_url) print("Sometimes they ask you to fill in a survey.") try: survey_layer = browser.find_element_by_id('ipeL104230') survey_layer.send_keys(Keys.ESCAPE) except NoSuchElementException: print("We're lucky, no survey on the LEGO shop today!") print("They want to know how old we are.") age_field = browser.find_element_by_name('rpAgeAndCountryAgeField') age_field.send_keys('55') age_field.send_keys(Keys.RETURN) if username and password: print("Let's log in with LEGO ID {user}.".format(user=username)) login_link = browser.find_element_by_css_selector('.legoid .links > a') login_link.click() browser.switch_to.frame('legoid-iframe') user_input = browser.find_element_by_id('fieldUsername') user_input.click() user_input.send_keys(username) passwd_input = browser.find_element_by_id('fieldPassword') passwd_input.click() passwd_input.send_keys(password) login_button = browser.find_element_by_id('buttonSubmitLogin') login_button.click() browser.switch_to.default_content() sleep(4) # seconds wait = WebDriverWait(browser, 5) print("We need to tell them which set we want to buy parts from: {lego_set}".format(lego_set=lego_set)) setno_field = wait.until(EC.element_to_be_clickable( (By.CSS_SELECTOR, '.product-search input[ng-model=productNumber]'))) setno_field.send_keys(lego_set) setno_field.send_keys(Keys.RETURN) print("Let's scroll the page down a bit, so we can see things better.") browser.execute_script("window.scroll(0, 750);") print("That's gonna be crazy: {count} elements to order! Let's rock.".format(count=len(order_list))) element_field = wait.until(EC.element_to_be_clickable( (By.ID, 'element-filter'))) print() for brick in order_list: part_no, quantity = brick.split(':') print("- {qty}x #{pn} ".format(qty=quantity, pn=part_no), end='') element_field.clear() element_field.send_keys(part_no) element_field.send_keys(Keys.RETURN) sleep(.3) # seconds try: add_button = browser.find_element_by_css_selector('.element-details + button') add_button.click() sleep(.2) # seconds except NoSuchElementException: print("OOOPS! No LEGO part with that number found in set #{set}. :-(".format(set=lego_set)) continue try: warn_msg = browser.find_element_by_css_selector('.alert-warning .sold-out-info') if warn_msg.is_displayed(): print("NOTE: item out of stock. ", end='') add_anyway = browser.find_element_by_css_selector('.alert-warning + .clearfix button') add_anyway.click() except NoSuchElementException: pass amount_select = browser.find_elements_by_css_selector('.bag-item select')[-1] amount_select.send_keys(quantity) amount_select.send_keys(Keys.TAB) selected = Select(amount_select).first_selected_option if quantity != selected.text: print("WARNING: Could not select desired quantity. {} != {}".format(quantity, selected.text)) else: print() browser.execute_script("window.scroll(0, 0);") print() print("We're done. You can finalize your order now. Thanks for watching!")
send_button.click() # enter the person's name you want to pay time.sleep(5) name_box = browser.find_element_by_class_name("onebox_prefill") name_box.click() name_text_box = browser.find_element_by_class_name("paddingUnifier") name_text_box.send_keys(venmoInfo.payee_name) name_text_box.send_keys(Keys.ENTER) payment_box = browser.find_element_by_class_name("mainTextBox") time.sleep(1) payment_box.click() datetime_now = datetime.datetime.now() SendKeys.SendKeys(venmoInfo.amount + venmoInfo.description, with_spaces=True) # click the pay button pay_button = browser.find_element_by_id("onebox_pay_toggle") pay_button.click() name_text_box = browser.find_element_by_class_name("paddingUnifier") name_text_box.send_keys(venmoInfo.payee_name) # click the send button send_button = browser.find_element_by_id("onebox_send_button") send_button.click() else: # click on the sign in link signin_link = browser.find_element_by_link_text("Sign in") signin_link.click() print("Couldn't find the cookie file, you will need two factor authorization and then cookie will be saved") # wait a while until the user fully signs in time.sleep(60)
class AutomatorMixin(object): class UnexpectedSituation(Exception): pass data_property_class = None def __init__(self, steps, data_args=[]): self.steps = steps self.data = self.data_property_class(*data_args) def run(self): options = ChromeOptions() options.add_argument('--test-type') self.driver = Chrome(chrome_options=options) self.perform_steps() self.driver.close() def find_element(self, selector): LOG.info('finding selector "%s"' % selector) return self.driver.find_element_by_css_selector(selector) @property def action_method_lookup(self): return self.get_action_method__lookup() def get_action_method__lookup(self): return { 'click': self.perform_click, 'fill_form': self.perform_fill_form, 'select_drop_down': self.perform_select_drop_down, } def get_css_selector(self, action): return action.get('css_selector') def get_action_value(self, action): if 'value' in action: value = action['value'] elif 'property' in action: property_name = action['property'] value = getattr(self.data, property_name) else: raise AutomatorMixin.UnexpectedSituation('Cannot find key "property" or "value"') return value def perform_steps(self): for step in self.steps: if 'url' in step: self.driver.get(step['url']) if 'actions' in step: self.perform_actions(step['actions']) def perform_actions(self, actions): for action in actions: action_method = self.action_method_lookup[action['type']] action_method(action) def perform_click(self, action): selector = self.get_css_selector(action) if selector: self.find_element(selector).click() return # Find by id. This will be needed when people use "." in their id names. Such as kfc's survey css_id = action['id_selector'] LOG.info(css_id) self.driver.find_element_by_id(css_id).click() def perform_fill_form(self, action): selector = self.get_css_selector(action) value = self.get_action_value(action) self.find_element(selector).send_keys(value) def perform_select_drop_down(self, action): selector = self.get_css_selector(action) value = self.get_action_value(action) Select(self.find_element(selector)).select_by_value(value)