def login(user_email_address, user_password, user_profile_url): """ user_email_address = str Your Email user_password = str Your password user_profile_url = str Your profile URL """ chrome_options = Options() prefs = { "profile.default_content_setting_values.notifications": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") driver = Chrome(options=chrome_options) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login = "******" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() driver.get(user_profile_url + '/friends') return driver
def delete_posts(user_email_address=None, user_password=None, user_profile_url=None): """ user_email_address: Your Email user_password: Your password user_profile_url: Your profile URL """ assert all((user_email_address, user_password, user_profile_url)), "Insufficient arguments provided" chrome_options = Options() prefs = {"profile.default_content_setting_values.notifications" : 2} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") driver = Chrome(chrome_options=chrome_options) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login="******" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() driver.get(user_profile_url) for _ in range(MAX_POSTS): post_button_sel = "_4xev" timeline_element = driver.find_element_by_class_name(post_button_sel) actions = ActionChains(driver) actions.move_to_element(timeline_element).click().perform() menu = driver.find_element_by_css_selector("#globalContainer > div.uiContextualLayerPositioner.uiLayer > div") actions.move_to_element(menu).perform() try: delete_button = menu.find_element_by_xpath("//a[@data-feed-option-name=\"FeedDeleteOption\"]") except: delete_button = menu.find_element_by_xpath("//a[@data-feed-option-name=\"HIDE_FROM_TIMELINE\"]") actions.move_to_element(delete_button).click().perform() confirmation_button = driver.find_element_by_class_name("layerConfirm") driver.execute_script("arguments[0].click();", confirmation_button) time.sleep(5) driver.refresh()
def runAttacks(url): INJECTION_QUERIES = [ "s'; SELECT password FROM users WHERE 1=1; --", "s'; DELETE FROM users WHERE 1=1; --", "1' OR 1=1 --", "%' or 1=1 --" ] driver = Chrome() #print(driver.request('POST', url)) driver.get(url) time.sleep(2) form1 = driver.find_element_by_name('txtField') try: form2 = driver.find_element_by_name('passField') except NoSuchElementException: print("passField not found") forms = driver.find_elements_by_tag_name('input') i = 0 keepGoing = True while keepGoing: # continue trying until we run out of queries for query in INJECTION_QUERIES: print("QUERY START: " + query) forms = driver.find_elements_by_tag_name('input') # we need to input our injections without knowing what inputs require other inputs to submit # so loop through every form element not being injected to and fill it with sample data for otherForm in forms: otherForm.send_keys(query) time.sleep(1) if not driver.request( 'POST', url ).ok: # returns true if http status code is less than 400 print("500!") print(query) #driver.close() #driver = Chrome() #.get(url) forms[i].submit() time.sleep(3) #break else: #if the form will submit without error, forms[i].submit() #submit the form time.sleep(3) #form.submit() driver.get(url) time.sleep(3) forms = driver.find_elements_by_tag_name('input') for form in forms: form.clear() time.sleep(2) i += 1 print("i " + str(i)) print("len forms: " + str(len(forms))) if (i >= len(forms)): keepGoing = False break driver.quit()
def get_web_driver(url, username, password): driver = Chrome() driver.get(url) driver.implicitly_wait(5) # seconds driver.find_element_by_name("username").send_keys(username) driver.find_element_by_name("password").send_keys(password) time.sleep(10) return driver
def get_web_driver(url, username, password): driver = Chrome() driver.get(url) driver.implicitly_wait(1) # seconds driver.switch_to_frame("login_page") driver.find_element_by_name("fldLoginUserId").send_keys(username) driver.implicitly_wait(3) driver.find_element_by_id('chkrsastu').click() driver.find_element_by_name("fldPassword").send_keys(password) driver.implicitly_wait(5) return driver
chrome_options.add_argument('--user-data-dir=/tmp/user-data') chrome_options.add_argument('--data-path=/tmp/data-path') chrome_options.add_argument('--homedir=/tmp') chrome_options.add_argument('--disk-cache-dir=/tmp/cache-dir') prefs={"profile.managed_default_content_settings.images": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs",prefs) delay = 60 chrome_options.binary_location = "/usr/bin/chromium-browser" driver = Chrome(executable_path=os.path.abspath("/usr/lib/chromium-browser/chromedriver"), chrome_options=chrome_options) print("logging into outlook") driver.get("https://outlook.office.com/owa/?ae=Folder&t=IPF.Appointment") try: driver.find_element_by_name("loginfmt").send_keys("*****@*****.**") driver.find_element_by_id("idSIButton9").click() print("entered username, waiting for password prompt") try: myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'branding'))) print("password prompt loaded") except TimeoutException: print("Loading password prompt took too much time!") driver.close(); exit(1) passwd = getpass.getpass() driver.find_element_by_id("passwordInput").send_keys(passwd) driver.find_element_by_id("submitButton").click()
# Set your minted.com email and password as the env vars: # minted_email and minted_password try: minted_email = os.environ['minted_email'] except KeyError: minted_email = input("Enter your minted.com email address:") try: minted_password = os.environ['minted_password'] except KeyError: minted_password = input("Enter your minted.com password:") driver.get(url) # Selenium deals with lgin form email_elem = driver.find_element_by_name('email') email_elem.send_keys(minted_email) password_elem = driver.find_element_by_name('password') password_elem.send_keys(minted_password) login_submit = driver.find_element_by_class_name('loginButton') login_submit.click() sleep(5) # to load JS and be nice # Request address book contents as json response = driver.request('GET','https://addressbook.minted.com/api/contacts/contacts/?format=json') listings = response.json() # Create dataframe to hold addresses address_book = pd.DataFrame(listings)
def login(user_email_address, user_password, user_profile_url, is_headless, two_factor_token): """ Attempts to log into Facebook Returns a driver object user_email_address: str Your Email user_password: str Your password user_profile_url: str Your profile URL """ # The Chrome driver is required because Gecko was having issues chrome_options = Options() prefs = { "profile.default_content_setting_values.notifications": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") if is_headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('log-level=2') driver = Chrome(options=chrome_options) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login = "******" approvals_code = "approvals_code" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() if "two-factor authentication" in driver.page_source.lower(): if two_factor_token: twofactorelement = driver.find_element_by_name(approvals_code) twofactorelement.send_keys(two_factor_token) # Submits after the code is passed into the form, does not validate 2FA code. contelement = driver.find_element_by_id("checkpointSubmitButton") contelement.click() # Defaults to saving this new browser, this occurs on each new automated login. save_browser = driver.find_element_by_id("checkpointSubmitButton") save_browser.click() else: # Allow time to enter 2FA code print("Pausing to enter 2FA code") time.sleep(20) print("Continuing execution") driver.get(user_profile_url) return driver
def get_amzn_driver(email, password, headless=False, session_path=None): chrome_options = ChromeOptions() if headless: chrome_options.add_argument('headless') chrome_options.add_argument('no-sandbox') chrome_options.add_argument('disable-dev-shm-usage') chrome_options.add_argument('disable-gpu') if session_path is not None: chrome_options.add_argument("user-data-dir=" + session_path) logger.info('Logging into Amazon.com') home_dir = os.path.expanduser("~") driver = Chrome(options=chrome_options, executable_path=get_stable_chrome_driver(home_dir)) driver.get(ORDER_HISTORY_URL_VIA_SWITCH_ACCOUNT_LOGIN) driver.implicitly_wait(2) def get_element_by_id(driver, id): try: return driver.find_element_by_id(id) except NoSuchElementException: pass return None def get_element_by_xpath(driver, xpath): try: return driver.find_element_by_xpath(xpath) except NoSuchElementException: pass return None # Go straight to the account switcher, and look for the given email. # If present, click on it! Otherwise, click on "Add account". desired_account_element = get_element_by_xpath( driver, "//div[contains(text(), '{}')]".format(email)) if desired_account_element: desired_account_element.click() driver.implicitly_wait(2) # It's possible this account has already authed recently. If so, the # next block will be skipped and the login is complete! if not get_element_by_id(driver, 'report-confirm'): driver.find_element_by_id('ap_password').send_keys( get_password(password)) driver.find_element_by_name('rememberMe').click() driver.find_element_by_id('signInSubmit').submit() else: # Cannot find the desired account in the switch. Log in via Add Account driver.find_element_by_xpath('//div[text()="Add account"]').click() driver.implicitly_wait(2) driver.find_element_by_id('ap_email').send_keys(email) # Login flow sometimes asks just for the email, then a # continue button, then password. if get_element_by_id(driver, 'continue'): driver.find_element_by_id('continue').click() driver.implicitly_wait(2) driver.find_element_by_id('ap_password').send_keys( get_password(password)) driver.find_element_by_name('rememberMe').click() driver.find_element_by_id('signInSubmit').submit() driver.implicitly_wait(2) if not get_element_by_id(driver, 'report-confirm'): logger.warning('Having trouble logging into Amazon. Please see the ' 'browser and complete login within the next 5 minutes. ' 'This script will continue automatically on success. ' 'You may need to manually navigate to: {}'.format( ORDER_HISTORY_REPORT_URL)) if get_element_by_id(driver, 'auth-mfa-otpcode'): logger.warning('Hint: Looks like an auth challenge! Maybe check ' 'your email') try: wait_cond = EC.presence_of_element_located((By.ID, 'report-confirm')) WebDriverWait(driver, 60 * 5).until(wait_cond) except TimeoutException: logger.critical('Cannot complete login!') exit(1) return driver
def delete_posts(user_email_address=None, user_password=None, user_profile_url=None): """ user_email_address: Your Email user_password: Your password user_profile_url: Your profile URL """ assert all((user_email_address, user_password, user_profile_url)), "Insufficient arguments provided" # The Chrome driver is required because Gecko was having issues chrome_options = Options() prefs = {"profile.default_content_setting_values.notifications": 2} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") driver = Chrome(chrome_options=chrome_options) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login = "******" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() if "Two-factor authentication" in driver.page_source: # Allow time to enter 2FA code print("Pausing to enter 2FA code") time.sleep(20) print("Continuing execution") driver.get(user_profile_url) for _ in range(MAX_POSTS): post_button_sel = "_4xev" timeline_element = driver.find_element_by_class_name(post_button_sel) actions = ActionChains(driver) actions.move_to_element(timeline_element).click().perform() menu = driver.find_element_by_css_selector( "#globalContainer > div.uiContextualLayerPositioner.uiLayer > div") actions.move_to_element(menu).perform() try: delete_button = menu.find_element_by_xpath( "//a[@data-feed-option-name=\"FeedDeleteOption\"]") # FIXME Using a bare except here to avoid having to handle all possible exceptions except: delete_button = menu.find_element_by_xpath( "//a[@data-feed-option-name=\"HIDE_FROM_TIMELINE\"]") actions.move_to_element(delete_button).click().perform() confirmation_button = driver.find_element_by_class_name("layerConfirm") # Facebook would not let me get focus on this button without some custom JS driver.execute_script("arguments[0].click();", confirmation_button) # Required to sleep the thread for a bit after using JS to click this button time.sleep(5) driver.refresh()
def send_outlook(): home_dir = str(Path.home()) chrome_cache_path = f"{home_dir}/.chrome_cache" print(f"loading chrome, caching to: {chrome_cache_path}") chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-startup-window") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-sync-preferences") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-background-networking") chrome_options.add_argument("--no-first-run") chrome_options.add_argument("--aggressive-tab-discard") chrome_options.add_argument("--user-agent=Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.2)") chrome_options.add_argument(f"--user-data-dir={chrome_cache_path}/user-data") chrome_options.add_argument(f"--data-path={chrome_cache_path}/data-path") chrome_options.add_argument(f"--disk-cache-dir={chrome_cache_path}/disk-cache") chrome_options.add_argument(f"--homedir={chrome_cache_path}") chrome_options.add_argument(f"--disk-cache-dir={chrome_cache_path}/cache-dir") prefs={"profile.managed_default_content_settings.images": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs",prefs) delay = 60 chrome_options.binary_location = "/usr/bin/chromium-browser" driver = Chrome(executable_path=os.path.abspath("/usr/lib/chromium-browser/chromedriver"), chrome_options=chrome_options) print("logging into outlook") driver.get("https://outlook.office.com/owa/") try: driver.find_element_by_name("loginfmt").send_keys("*****@*****.**") driver.find_element_by_id("idSIButton9").click() print("entered username, waiting for password prompt") try: myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'passwordInput'))) print("password prompt loaded") except TimeoutException: print("Loading password prompt took too much time!") print(driver.page_source) driver.close(); exit(1) passwd = getpass.getpass() driver.find_element_by_id("passwordInput").send_keys(passwd) driver.find_element_by_id("submitButton").click() print("entered password, waiting for 2FA token") try: myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'idSIButton9'))) driver.find_element_by_id("idSIButton9").click() print("asking to remember credentials for next time") except TimeoutException: print("Loading 2FA page took too much time!") print(driver.page_source) driver.close(); exit(1) print("2FA accepted, loading office landing page") except NoSuchElementException: print("already logged in") try: print("waiting for landing page to load") myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'lnkBrwsAllFldrs'))) except TimeoutException: print(driver.page_source) print("Loading landing page too much time!") driver.close(); exit(1) try: eink.send_update("Loading Tasks") print("loading tasks") driver.find_element_by_id("lnkBrwsAllFldrs").click() driver.find_element_by_id("selbrfld").click() Select(driver.find_element_by_id("selbrfld")).select_by_visible_text("Tasks") driver.find_element_by_id("selbrfld").click() driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Sent Items'])[1]/following::img[1]").click() myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.CLASS_NAME, 'lvw'))) except TimeoutException: print(driver.page_source) print("Loading todo list took too much time!") driver.close(); exit(1) elements = driver.find_elements_by_css_selector("td h1 a") for i, element in enumerate(elements): eink.send_todo(i, element.text) try: eink.send_update("Loading Calendar") print("loading calendar") driver.find_element_by_id("lnkNavCal").click() myElem = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.CLASS_NAME, 'cntnttp'))) print("calendar loaded, dumping entries") except TimeoutException: print(driver.page_source) print("Loading calendar took too much time!") driver.close(); exit(1) elements = driver.find_elements_by_css_selector("td.v a") for i, element in enumerate(elements): eink.send_meeting(i,element.get_attribute('title'))
def get_amzn_driver(email, password, headless=False, session_path=None): zip_type = "" executable_path = os.path.join(os.getcwd(), 'chromedriver') if _platform in ['win32', 'win64']: executable_path += '.exe' zip_type = CHROME_ZIP_TYPES.get(_platform) if not os.path.exists(executable_path): zip_file_url = CHROME_DRIVER_BASE_URL.format(CHROME_DRIVER_VERSION, zip_type) request = requests.get(zip_file_url) if request.status_code != 200: raise RuntimeError( 'Error finding chromedriver at {}, status = {}'.format( zip_file_url, request.status_code)) zip_file = zipfile.ZipFile(io.BytesIO(request.content)) zip_file.extractall() os.chmod(executable_path, 0o755) chrome_options = ChromeOptions() if headless: chrome_options.add_argument('headless') chrome_options.add_argument('no-sandbox') chrome_options.add_argument('disable-dev-shm-usage') chrome_options.add_argument('disable-gpu') # chrome_options.add_argument("--window-size=1920x1080") if session_path is not None: chrome_options.add_argument("user-data-dir=" + session_path) logger.info('Logging into Amazon.com') driver = Chrome(chrome_options=chrome_options, executable_path=executable_path) driver.get(ORDER_HISTORY_URL_VIA_SWITCH_ACCOUNT_LOGIN) driver.implicitly_wait(2) def get_element_by_id(driver, id): try: return driver.find_element_by_id(id) except NoSuchElementException: pass return None def get_element_by_xpath(driver, xpath): try: return driver.find_element_by_xpath(xpath) except NoSuchElementException: pass return None # Go straight to the account switcher, and look for the given email. # If present, click on it! Otherwise, click on "Add account". desired_account_element = get_element_by_xpath( driver, "//div[contains(text(), '{}')]".format(email)) if desired_account_element: desired_account_element.click() driver.implicitly_wait(2) # It's possible this account has already authed recently. If so, the # next block will be skipped and the login is complete! if not get_element_by_id(driver, 'report-confirm'): driver.find_element_by_id('ap_password').send_keys( get_password(password)) driver.find_element_by_name('rememberMe').click() driver.find_element_by_id('signInSubmit').submit() else: # Cannot find the desired account in the switch. Log in via Add Account driver.find_element_by_xpath('//div[text()="Add account"]').click() driver.implicitly_wait(2) driver.find_element_by_id('ap_email').send_keys(email) driver.find_element_by_id('ap_password').send_keys( get_password(password)) driver.find_element_by_name('rememberMe').click() driver.find_element_by_id('signInSubmit').submit() driver.implicitly_wait(2) if not get_element_by_id(driver, 'report-confirm'): logger.warning('Having trouble logging into Amazon. Please see the ' 'browser and complete login within the next 5 minutes. ' 'This script will continue automatically on success. ' 'You may need to manually navigate to: {}'.format( ORDER_HISTORY_REPORT_URL)) if get_element_by_id(driver, 'auth-mfa-otpcode'): logger.warning('Hint: Looks like an auth challenge! Maybe check ' 'your email') try: wait_cond = EC.presence_of_element_located((By.ID, 'report-confirm')) WebDriverWait(driver, 60 * 5).until(wait_cond) except TimeoutException: logger.critical('Cannot complete login!') exit(1) return driver
class Task: #takes arguments and creates class attributes for easier and prettier access def __init__(self, name, incart, checkout, settings): self.cart = [] #array of item objects to cart and checkout self.settings = settings #dictionairy of user settings for item in incart: self.cart.append( Item(item, self.settings )) #convert array of arrays to array of item objects self.checkout = checkout #dictionairy of checkout values (such as name, address, ect) self.name = name #name of task to be used during printing to console #creates a selenium webdriver def create_webdriver(self): #https://stackoverflow.com/questions/29916054/change-user-agent-for-selenium-driver opts = Options() self.useragent = random_user_agent() #calls for a random useragent opts.add_argument("user-agent=" + self.useragent) #adds random user agent to options self.webdriver = Chrome( executable_path=get_local_directory() + '/resources/chromedriver', chrome_options=opts) #creates new webdriver with premade options self.webdriver.set_page_load_timeout(int( self.settings["timeout"])) #set timeout of pageload from config #attempts to cart every item in cart. Returns true if any of the items cart def cart_items(self): self.create_webdriver() return_bool = False for item in self.cart: if (item.in_cart == False): item.cart(self.webdriver) if (item.in_cart == True): return_bool = True return return_bool #loads checkout page, fills form, clicks checkout, waits for user to complete captcha def manual_checkout(self): self.webdriver.get( 'https://www.supremenewyork.com/checkout') #load the checkout page self.fill_form() self.webdriver.find_element_by_name("commit").click() if (self.wait_for_manual_captcha()): return self.confirmation() #fills all elements of form and check required check boxes def fill_form(self): #TODO: IF SITEKEY CHANGED, CLEAR OLD TOKENS (not high priority) update_sitekey( self.webdriver.find_element_by_xpath( '//*[@id="cart-cc"]/fieldset/div[3]').get_attribute( "data-sitekey") ) #updates the captcha sitekey saved on file (in case it changed). self.webdriver.find_element_by_name("order[billing_name]").send_keys( self.checkout["name"]) self.webdriver.find_element_by_name("order[email]").send_keys( self.checkout["email"]) self.webdriver.find_element_by_name("order[tel]").send_keys( self.checkout["phone"]) self.webdriver.find_element_by_name( "order[billing_address]").send_keys(self.checkout["address"]) self.webdriver.find_element_by_name("order[billing_zip]").send_keys( self.checkout["zipcode"]) self.webdriver.find_element_by_name("order[billing_city]").send_keys( self.checkout["city"]) self.webdriver.find_element_by_name("order[billing_state]").send_keys( self.checkout["state"]) self.webdriver.find_element_by_name( "order[billing_country]").send_keys(self.checkout["country"]) checkout_field = self.webdriver.find_element_by_name( "credit_card[nlb]") for character in list( self.checkout["card_number"] ): #weird error occurs when you send all at once,was shuffling characters time.sleep(.01) checkout_field.send_keys(character) self.webdriver.find_element_by_name("credit_card[month]").send_keys( self.checkout["card_month"]) self.webdriver.find_element_by_name("credit_card[year]").send_keys( self.checkout["card_year"]) self.webdriver.find_element_by_name("credit_card[rvv]").send_keys( self.checkout["cvv"]) self.webdriver.find_element_by_xpath( "//*[@id='cart-cc']/fieldset/p[2]/label/div/ins").click() #loads checkout page, fills form(supreme supplies necessary cookies during form filling, so even though I never submit I need to fill the form) def ajax_checkout(self): self.webdriver.get('https://www.supremenewyork.com/checkout') if ("y" in self.settings["fill_form"]): try: self.fill_form() except NoSuchElementException: pass csrf_token = self.webdriver.find_element_by_name( 'csrf-token').get_attribute("content") #headers required to make AJAX request, found using chrome devtools headers = { 'Accept': '*/*', 'X-CSRF-Token': csrf_token, 'X-Requested-With': 'XMLHttpRequest', 'Referer': 'https://www.supremenewyork.com/checkout', 'Accept-Language': 'en-US,en;q=0.8', 'User-Agent': self.useragent, 'Connection': 'keep-alive', #'Host':'wwww.supremenewyork.com', 'Origin': 'https://www.supremenewyork.com', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Length': '1006', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } #payload required to make AJAX request, found using chrome devtools payload = { 'utf8': '✓', 'authenticity_token': csrf_token, 'order[billing_name]': self.checkout['name'], 'order[email]': self.checkout['email'], 'order[tel]': self.checkout['phone'], 'order[billing_address]': self.checkout['address'], 'order[billing_address_2]': '', 'order[billing_zip]': self.checkout['zipcode'], 'order[billing_city]': self.checkout['city'], 'order[billing_state]': self.checkout['state'], 'order[billing_country]': self.checkout['country'], 'same_as_billing_address': '1', 'asec': 'Rmasn', 'store_credit_id': '', 'credit_card[nlb]': self.checkout["card_number"], 'credit_card[month]': self.checkout["card_month"], 'credit_card[year]': self.checkout["card_year"], 'credit_card[rvv]': self.checkout["cvv"], 'order[terms]': '0', 'order[terms]': '1', 'credit_card[vval]': self.checkout["cvv"], 'g-recaptcha-response': get_captcha() } #make request, print response response = self.webdriver.request( 'POST', 'https://www.supremenewyork.com/checkout.json', data=payload, headers=headers) print "[" + self.name + "] RESPONSE: " + response.text #looks to see if captchas solved yet def wait_for_manual_captcha(self): while (True): #trys to click checkout, if captcha is visible it will throw WebDriverException try: self.webdriver.find_element_by_name("commit").click() return True except WebDriverException: print "[" + self.name + "] Fill captcha manually..." time.sleep(3) #finds result of checkout on confirmation page def confirmation(self): while True: try: if ('selected' in self.webdriver.find_element_by_xpath( '//*[@id="tabs"]/div[3]').get_attribute('class') ): #if the confirmation tab is selected print "[" + self.name + "] Response: " + self.webdriver.find_element_by_id( 'content' ).text.split("CONFIRMATION")[ 1] #print the desired information from checkout page return True except (NoSuchElementException, StaleElementReferenceException ): #thrown if tab is not selected print "[" + self.name + "] Waiting for confirmation..." time.sleep(1)
class ObjSup: def __init__(self): print self.start = time.time() with open('settings.json', 'r') as settingsFile: self.settings = json.loads(settingsFile.read()) self.headers = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8', 'Cache-Control': 'max-age=0', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36' } self.session = Chrome( '/Users/alex/PycharmProjects/FirstSelenium/chromedriver') self.session.headers = self.headers self.found_link = '' self.style_id = '' self.prod_id = '' self.form_key = '' def cook(self): self.log('Starting up') self.log('Attempting to scrape category {}'.format( self.settings['category'])) if self.scrape_product(): self.log('Attempting ATC') if self.add_to_cart(): self.log('Attempting checkout') if self.checkout(): self.log('Checked out') else: self.log('Failed to check out') else: self.log('Failed to ATC') else: self.log('Failed to scrape category') def log(self, text): current = datetime.now() print('== {} == {}'.format(colored(str(current), 'blue'), str(text))) def scrape_product(self): cat_url = 'http://supremenewyork.com/shop/all/{}'.format( self.settings['category']) url_arr = [] name_arr = [] style_arr = [] self.log('Opening category page') r = self.session.request('GET', cat_url, verify=False) if r.status_code != 200: self.log('Encountered bad status code {}'.format(r.status_code)) return False soup = BeautifulSoup(r.text, 'html.parser') for link in soup.select('a.name-link'): url = link.get('href') if url_arr.count(url) == 0: name_arr.append(link.get_text()) url_arr.append(url) else: style_arr.append(link.get_text()) self.log('Found {} products ( {} names / {} styles)'.format( str(len(url_arr)), str(len(name_arr)), str(len(style_arr)))) self.log('Checking against keyword "{}" & style "{}"'.format( self.settings['name_key'], self.settings['style_key'])) for i in range(0, len(url_arr)): if self.settings['name_key'] in name_arr[i].lower(): if self.settings['style_key'] in style_arr[i].lower(): self.found_link = url_arr[i] self.log('Found matching link {}'.format(self.found_link)) return True if not self.found_link: self.log('Did not find a matching link') return False def add_to_cart(self): url = 'http://supremenewyork.com/{}.json'.format(self.found_link) self.log("Opening product JSON") r = self.session.request('GET', url, verify=False) if r.status_code != 200: self.log('Encountered bad status {} opening product JSON'.format( r.status_code)) return False j = r.json() self.log('Getting IDs') for e in j['styles']: if e['name'].lower() == self.settings['style_key']: self.style_id = e['id'] self.log('Found style ID {}'.format(self.style_id)) for s in e['sizes']: if s['name'].lower() == self.settings['size_key']: if s['stock_level'] == 1: self.prod_id = s['id'] self.log('Found product ID {}'.format( self.prod_id)) if s['stock_level'] == 0: self.log('Out of stock') return False # The form key entry point seems to be not working at the moment # self.log('Looking for form key') # url = 'http://supremenewyork.com/{}'.format(self.found_link) # r = self.session.request("GET", url, verify=False) # if r.status_code != 200: # self.log('Bad status code {} when looking for form key'.format(r.status_code)) # return False # soup = BeautifulSoup(r.text, 'html.parser') # sources = soup.findAll('form', {"action": True}) # for s in sources: # self.form_key = s['action'] # self.log('Found form key {}'.format(self.form_key)) # time.sleep(2) # url = 'http://www.supremenewyork.com/{}'.format(self.form_key) # p = "commit=add%20to%20cart&style={}&size={}&utf8=%E2%9C%93".format(self.style_id, self.prod_id) # r = self.session.request('POST', url, data=p, verify=False) # if r.status_code != 200: # self.log('Bad status code {} when firing form POST'.format(r.status_code)) # return False self.session.get('http://www.supremenewyork.com/{}'.format( self.found_link)) s = Select(self.session.find_element_by_xpath("//select[@id='size']")) s.select_by_value(str(self.prod_id)) button = self.session.find_element_by_name("commit") button.click() time.sleep(1) self.log('Checking cart contents') r = self.session.request( 'GET', 'http://www.supremenewyork.com/shop/cart.json', verify=False) if str(self.prod_id) not in r.text: self.log('Product ID not in cart contents') return False return True def checkout(self): # This is a collection of the form elements. The selectors might change # so I try and adapt by using tab keys. self.session.get('https://www.supremenewyork.com/checkout') self.log('Finding form elements') name = self.session.find_element_by_id('order_billing_name') # email = self.session.find_element_by_id('order_email') tel = self.session.find_element_by_id('order_tel') # add = self.session.find_element_by_name('order[billing_address]') # ad2 = self.session.find_element_by_name('order[billing_address_2]') # zip = self.session.find_element_by_id('order_billing_zip') # city = self.session.find_element_by_id('order_billing_city') # state = Select(self.session.find_element_by_id('order_billing_state')) # country = Select(self.session.find_element_by_id('order_billing_country')) ctype = Select(self.session.find_element_by_id('credit_card_type')) # cc = self.session.find_element_by_name('order[cnb]') xm = Select(self.session.find_element_by_id('credit_card_month')) xy = Select(self.session.find_element_by_id('credit_card_year')) # cvv = self.session.find_element_by_xpath("//input[@size='4']") submit = self.session.find_element_by_xpath("//input[@type='submit']") self.log('Entering checkout details') name.send_keys(self.settings['f_name'] + ' ' + self.settings['l_name'], Keys.TAB, self.settings['email'], Keys.TAB) tel.send_keys(self.settings['phone'], Keys.TAB, self.settings['address'], Keys.TAB, self.settings['address2'], Keys.TAB, self.settings['zip'], Keys.TAB) ctype.select_by_visible_text(self.settings['type']) cardchain = ActionChains(self.session) cardchain.send_keys(Keys.TAB, self.settings['cc']) cardchain.perform() xm.select_by_value(self.settings['month']) xy.select_by_value(self.settings['year']) cvvchain = ActionChains(self.session) cvvchain.send_keys(Keys.TAB, self.settings['cvv'], Keys.TAB, Keys.SPACE) cvvchain.perform() # This is the delay you want to set to avoid ghost checkout time.sleep(self.settings['delay']) submit.click() return True
def get_token(driver: Chrome): value_json = driver.find_element_by_name("javascript-user").get_attribute( "value") return json.loads(value_json)["token"]
def login(user_email_address, user_password, is_headless, two_factor_token): """ Attempts to log into Facebook Returns a driver object user_email_address: str Your Email user_password: str Your password user_profile_url: str Your profile URL """ # The Chrome driver is required because Gecko was having issues chrome_options = Options() prefs = { "profile.default_content_setting_values.notifications": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") if is_headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('log-level=2') try: driver = Chrome(options=chrome_options) except Exception as e: # The user does not have chromedriver installed # Tell them to install it stderr.write(str(e)) stderr.write(no_chrome_driver) exit(1) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login = "******" approvals_code = "approvals_code" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() # Defaults to no 2fa has_2fa = False try: # If this element exists, we've reached a 2FA page driver.find_element_by_xpath("//form[@class=\"checkpoint\"]") driver.find_element_by_xpath("//input[@name=\"approvals_code\"]") has_2fa = True except NoSuchElementException: has_2fa = "two-factor authentication" in driver.page_source.lower( ) or has_2fa if has_2fa: print(""" Two-Factor Auth is enabled. Please file an issue at https://github.com/weskerfoot/DeleteFB/issues if you run into any problems """) if two_factor_token and has_2fa: twofactorelement = driver.find_element_by_name(approvals_code) twofactorelement.send_keys(two_factor_token) # Submits after the code is passed into the form, does not validate 2FA code. contelement = driver.find_element_by_id("checkpointSubmitButton") contelement.click() # Defaults to saving this new browser, this occurs on each new automated login. save_browser = driver.find_element_by_id("checkpointSubmitButton") save_browser.click() elif has_2fa: # Allow time to enter 2FA code print("Pausing to enter 2FA code") time.sleep(35) print("Continuing execution") else: pass return driver
def delete_posts(user_email_address, user_password, user_profile_url, is_headless): """ user_email_address: str Your Email user_password: str Your password user_profile_url: str Your profile URL """ # The Chrome driver is required because Gecko was having issues chrome_options = Options() prefs = { "profile.default_content_setting_values.notifications": 2, 'disk-cache-size': 4096 } chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") if is_headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('log-level=2') driver = Chrome(options=chrome_options) driver.implicitly_wait(10) driver.get("https://facebook.com") email = "email" password = "******" login = "******" emailelement = driver.find_element_by_name(email) passwordelement = driver.find_element_by_name(password) emailelement.send_keys(user_email_address) passwordelement.send_keys(user_password) loginelement = driver.find_element_by_id(login) loginelement.click() if "Two-factor authentication" in driver.page_source: # Allow time to enter 2FA code print("Pausing to enter 2FA code") time.sleep(20) print("Continuing execution") driver.get(user_profile_url) for _ in range(MAX_POSTS): post_button_sel = "_4xev" while True: try: timeline_element = driver.find_element_by_class_name( post_button_sel) actions = ActionChains(driver) actions.move_to_element(timeline_element).click().perform() menu = driver.find_element_by_css_selector( "#globalContainer > div.uiContextualLayerPositioner.uiLayer > div" ) actions.move_to_element(menu).perform() try: delete_button = menu.find_element_by_xpath( "//a[@data-feed-option-name=\"FeedDeleteOption\"]") except SELENIUM_EXCEPTIONS: delete_button = menu.find_element_by_xpath( "//a[@data-feed-option-name=\"HIDE_FROM_TIMELINE\"]") actions.move_to_element(delete_button).click().perform() confirmation_button = driver.find_element_by_class_name( "layerConfirm") # Facebook would not let me get focus on this button without some custom JS driver.execute_script("arguments[0].click();", confirmation_button) except SELENIUM_EXCEPTIONS: continue else: break # Required to sleep the thread for a bit after using JS to click this button time.sleep(5) driver.refresh()
class app: def __init__(self): self.driver = Chrome(ChromeDriverManager().install()) self.url = 'http://93.188.161.218/' self.user = '' self.password = '' self.arr_dados_planilha = [] #False apenas para gerar o .exe if (False): self.caminho_planilha_exe = 'planilha_insert.xls' else: self.caminho_planilha_exe = '../../planilha_insert.xls' self.ler_planilha() def iniciar(self): print( ' \n ------------------------- Iniciando aplicação... ------------------------- \n' ) self.input_html() print( '\n ------------------------- Finalizando aplicação... -------------------------' ) def input_html(self): self.login() for dados_planilha in self.arr_dados_planilha: self.input_dados(dados_planilha) time.sleep(2) def ler_planilha(self): planilha = xlrd.open_workbook(self.caminho_planilha_exe) dados = planilha.sheet_by_index(0) row_skip_line = 0 for coluna in range(dados.nrows): if row_skip_line == 0: row_skip_line = 1 else: self.arr_dados_planilha.append(dados.row(coluna)) return self.arr_dados_planilha def login(self): self.driver.get(self.url) time.sleep(3) if self.user and self.password: self.driver.find_element_by_id('login').send_keys(self.user) self.driver.find_element_by_id('password').send_keys(self.password) self.driver.find_element_by_name('avancar').send_keys(Keys.ENTER) time.sleep(1) self.driver.get(f'{self.url}gerenciador/lancarDespesa.php') time.sleep(1) else: print('Usuário ou Senha não informado!') exit() def input_dados(self, arr_dados): planilha = xlrd.open_workbook(self.caminho_planilha_exe) dt_venc = xlrd.xldate.xldate_as_datetime(arr_dados[4].value, planilha.datemode) dt_venc = datetime.strftime(dt_venc, '%d/%m/%Y') self.driver.find_element_by_id('nome').send_keys( str(arr_dados[0].value)) self.driver.find_element_by_id('cpfOuCnpj').send_keys( str(arr_dados[1].value)) self.driver.find_element_by_id('val').send_keys(str( arr_dados[2].value)) self.driver.find_element_by_id('obs').send_keys(str( arr_dados[3].value)) self.driver.find_element_by_id('venc').send_keys(str(dt_venc)) self.driver.find_element_by_id('con').send_keys(str( arr_dados[5].value)) self.driver.find_element_by_id('ndoc').send_keys( str(arr_dados[6].value)) self.driver.find_element_by_name('add').send_keys(Keys.ENTER) time.sleep(3)