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 login(): driver = Chrome('/Users/liuxian/Downloads/chromedriver') driver.get("https://www.tianyancha.com/") driver.maximize_window() # 点击登录链接 # loginLink = WebDriverWait(driver, 30).until(lambda x:x.find_element_by_xpath('//a[@onclick="header.loginLink(event)"]')) loginLink = WebDriverWait( driver, 30).until(lambda x: x.find_element_by_xpath('//a[text()="登录/注册"]')) print(loginLink.text) loginLink.click() # 切换到密码登录方式 # login_by_pwd = WebDriverWait(driver, 30).until(lambda x:x.find_element_by_xpath('//div[@onclick="loginObj.changeCurrent(1);"]')) login_by_pwd = WebDriverWait( driver, 30).until(lambda x: x.find_element_by_xpath('//div[text()="密码登录"]')) print(login_by_pwd.text) login_by_pwd.click() # 输入用户名 username = WebDriverWait(driver, 30).until( lambda x: x.find_elements_by_xpath('//input[@type="text"]')[4]) username.send_keys('13926278814') # username.send_keys('13261731251') # 输入密码 password = WebDriverWait( driver, 30).until(lambda x: x.find_element_by_css_selector( 'div.input-warp.-block > input.input.contactword')) password.send_keys('liubing0220') # password.send_keys('lx109718') # 取消登录保留一周的选项 # saveoneweek = WebDriverWait(driver, 30).until(lambda x: x.find_element_by_css_selector('input.contactautoLogin')) # saveoneweek.click() # 点击登录按钮 # login_button = WebDriverWait(driver, 30).until(lambda x:x.find_element_by_xpath('//div[@onclick="loginObj.loginByPhone(event);"]')) login_button = WebDriverWait( driver, 30).until(lambda x: x.find_element_by_xpath('//div[text()="登录"]')) print(login_button.text) driver.execute_script("arguments[0].click();", login_button) print('开始自动登录...') time.sleep(15) print('登录完成。') open(driver, detail_url) print('请手动通过验证码...') time.sleep(20) response = driver.request( 'GET', 'https://dis.tianyancha.com/dis/getInfoById/3027736699.json?') print(response) cookie = get_cookie(driver) return cookie
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()
driver.find_element_by_id("weblogin_password").send_keys(UW_PASSWORD) driver.find_element_by_id("submit_button").click() time.sleep(1) driver.find_element_by_xpath('//button[normalize-space()="Continue"]').click() time.sleep(1) driver.find_element_by_xpath('//button[normalize-space()="New referral"]').click() # start for a browser automation approach # CREATE A CHILD driver.find_element_by_id("childFirstName").send_keys('Cindy') driver.find_element_by_id("childLastName").send_keys('Martin') driver.find_element_by_id("childDateOfBirth").send_keys('02/03/2020') driver.find_element_by_xpath("//html").click() sex = driver.find_element_by_id("sexOfChildIsFemale") driver.execute_script("arguments[0].click();", sex) driver.find_element_by_xpath("//html").click() # wait for child search time.sleep(2) continueWithoutMatchRadio = driver.find_element_by_id("continueWithoutMatch") driver.execute_script("arguments[0].click();", continueWithoutMatchRadio) # CREATE A REFERRAL continueButton = driver.find_element_by_xpath('//button[normalize-space()="Continue"]') driver.execute_script("arguments[0].click();", continueButton) time.sleep(1) # Primary Contact Name driver.find_element_by_id("primaryContactFirstName").send_keys("Carol") driver.find_element_by_id("primaryContactLastName").send_keys('Tyler') # Primary Contact Address driver.find_element_by_id("primaryContactPhysicalAddressAddress1").send_keys('4222 Clinton Way')
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()
class Magister: def __init__(self, url, username, password): self.bearer = None # enable browser logging d = DesiredCapabilities.CHROME d['loggingPrefs'] = {'browser': 'ALL'} self.server = Server("BrowserMob\\bin\\browsermob-proxy") cli.print_info("Starting proxy server...") self.server.start() self.proxy = self.server.create_proxy() cli.add_to_print("OK\n\n") cli.print_warning("NOTE: Connections will show as INSECURE!\n") options = webdriver.ChromeOptions() self.url = url options.add_argument("--proxy-server={0}".format(self.proxy.proxy)) cli.print_info("Browser started\n") self.browser = Chrome(options=options, executable_path="./chromedriver.exe", desired_capabilities=d) self.username = username self.password = password del password del username def destroy_creds(self): self.password = "******" self.username = "******" del self.password del self.username def dispose(self): self.browser.quit() destroy_creds() def login(self): browser = self.browser browser.get(self.url) time.sleep(5) cli.print_info("Attempting logon\n") try: self.proxy.new_har("LoginFlow") un = browser.find_element_by_id("username") un.clear() un.send_keys(self.username) un.send_keys(Keys.ENTER) time.sleep(0.5) pd = browser.find_element_by_id("password") pd.clear() pd.send_keys(self.password) bt = browser.find_element_by_id("password_submit") bt.click() except exceptions.NoSuchElementException: cli.print_error("Login Failed: Elements not found!\n") return False time.sleep(5) # Test if we're actually logged in try: test = browser.find_element_by_id("menu-activiteiten") cli.print_success("Login OK!\n") del test self.destroy_creds() return True except exceptions.NoSuchElementException: cli.print_error("Login Failed: Menu not found\n") return False def get_bearer(self): cli.print_info("Trying to get Authorization bearer from HAR...\n") data = self.proxy.har for d in data['log']['entries']: if ('response' in d): l = d['response']['redirectURL'].find("access_token=") if l != -1: cli.print_success("Autorization bearer obtained!\n") e = d['response']['redirectURL'].find("&token_type") self.bearer = d['response']['redirectURL'][l + 13:e] return True cli.print_error("Could not obtain Authorization bearer!\n") return False # Heheh MiTM JS def inject_test(self): cli.print_info("Testing JS Injection...") self.browser.execute_script('console.log("INJECT OK!");') # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': if 'INJECT OK!' in entry['message']: cli.add_to_print("OK\n") return True cli.add_to_print("FAILED\n") def GET(self, url): cli.print_info("Injecting JS for GET request\n") js = f""" $.ajax({{ type : "GET", url : "{url}", beforeSend: function(xhr){{xhr.setRequestHeader('Authorization', 'Bearer {self.bearer}');}}, success : function(result) {{ console.log("CALLBACK-GET: " + JSON.stringify(result)); }}, error : function(result) {{ console.log("CALLBACKE-GET: " + JSON.stringify(result)); }} }}); """ self.browser.execute_script(js) time.sleep(0.2) # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': e = entry['message'].find("CALLBACKE") i = entry['message'].find("CALLBACK") if (e != -1): cli.print_error(f"ERROR: {entry['message']}\n") elif (i != -1): cli.print_success(f"OK: {entry['message']}\n") else: cli.print_warning("WARNING: NO FEEDBACK GIVEN\n") # Inject a script! def POST(self, url, data): cli.print_info("Injecting JS for POST request\n") js = f""" $.ajax({{ type : "POST", url : "{url}", data: "{data}", beforeSend: function(xhr){{xhr.setRequestHeader('Authorization', 'Bearer {self.bearer}');}}, success : function(result) {{ console.log("CALLBACK-POST: " + JSON.stringify(result)); }}, error : function(result) {{ console.log("CALLBACKE-POST: " + JSON.stringify(result)); }} }}); """ self.browser.execute_script(js) time.sleep(0.2) # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': e = entry['message'].find("CALLBACKE") i = entry['message'].find("CALLBACK") if (e != -1): cli.print_error(f"ERROR: {entry['message']}\n") return False elif (i != -1): cli.print_success(f"OK: {entry['message']}\n") return True else: cli.print_warning("WARNING: NO FEEDBACK GIVEN\n") return False return False
class Magister: def __init__(self, url, username=None, password=None, *, verbose=False): self.bearer = None # enable browser logging d = DesiredCapabilities.CHROME d['loggingPrefs'] = {'browser': 'ALL'} self.server = Server("BrowserMob\\bin\\browsermob-proxy") logging.info("Starting proxy server...") self.server.start() self.proxy = self.server.create_proxy() logging.info("Proxy Server has started!") logging.warning("NOTE: Connections will show as INSECURE!\n") options = webdriver.ChromeOptions() self.url = url options.add_argument("--proxy-server={0}".format(self.proxy.proxy)) logging.info("Browser started\n") self.browser = Chrome(options=options, executable_path="./chromedriver.exe", desired_capabilities=d) self.username = username self.password = password del password del username def destroy_creds(self): self.password = "******" self.username = "******" del self.password del self.username def dispose(self): self.browser.quit() self.server.stop() self.destroy_creds() def login(self): browser = self.browser browser.get(self.url) time.sleep(5) self.proxy.new_har("LoginFlow") if self.username != None: logging.info("Attempting logon\n") try: un = browser.find_element_by_id("username") un.clear() un.send_keys(self.username) un.send_keys(Keys.ENTER) time.sleep(0.5) pd = browser.find_element_by_id("password") pd.clear() pd.send_keys(self.password) bt = browser.find_element_by_id("password_submit") bt.click() except exceptions.NoSuchElementException: logging.critical("Login Failed: Elements not found!\n") return False else: wait = WebDriverWait(browser, 30, poll_frequency=1) wait.until(EC.element_to_be_clickable((By.ID, 'password_submit'))) wait.until( EC.visibility_of_element_located((By.ID, "menu-activiteiten"))) time.sleep(5) # Test if we're actually logged in try: test = browser.find_element_by_id("menu-activiteiten") logging.info("Login OK!\n") del test self.destroy_creds() return True except exceptions.NoSuchElementException: logging.critical("Login Failed: Menu not found\n") return False def get_bearer(self): logging.info("Trying to get Authorization bearer from HAR...\n") try: data = self.proxy.har for d in data['log']['entries']: if ('response' in d): l = d['response']['redirectURL'].find("access_token=") if l != -1: logging.info("Autorization bearer obtained!\n") e = d['response']['redirectURL'].find("&token_type") self.bearer = d['response']['redirectURL'][l + 13:e] return True except Exception as e: logging.debug(e) logging.error("Could not obtain Authorization bearer!\n") return False # Heheh MiTM JS def inject_test(self): logging.info("Testing JS Injection...") self.browser.execute_script('console.log("INJECT OK!");') # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': if 'INJECT OK!' in entry['message']: logging.info('Injection success!') return True def GET(self, url): logging.info("Injecting JS for GET request\n") js = f""" $.ajax({{ type : "GET", url : "{url}", beforeSend: function(xhr){{xhr.setRequestHeader('Authorization', 'Bearer {self.bearer}');}}, success : function(result) {{ console.log("CALLBACK-GET: " + JSON.stringify(result)); }}, error : function(result) {{ console.log("CALLBACKE-GET: " + JSON.stringify(result)); }} }}); """ self.browser.execute_script(js) time.sleep(0.75) # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': e = entry['message'].find("CALLBACKE") i = entry['message'].find("CALLBACK") if (e != -1): logging.critical(f"ERROR: {entry['message']}\n") self.browser.execute_script("console.clear();") return False elif (i != -1): #logging.info(f"OK: {entry['message']}\n") e = entry['message'] # Reformat voor die dingejes s1 = 34 s2 = 34 try: s1 = e.index('{') except ValueError: pass try: s2 = e.index('[') except ValueError: pass s = None if s1 < s2: s = s1 else: s = s2 self.browser.execute_script("console.clear();") return e[s:len(e) - 1].replace("\\\"", "\"") else: logging.error("NO FEEDBACK GIVEN\n") self.browser.execute_script("console.clear();") return None # Inject a script! def POST(self, url, data): logging.info("Injecting JS for POST request\n") js = f""" $.ajax({{ type : "POST", url : "{url}", data: "{data}", beforeSend: function(xhr){{xhr.setRequestHeader('Authorization', 'Bearer {self.bearer}');}}, success : function(result) {{ console.log("CALLBACK-POST: " + JSON.stringify(result)); }}, error : function(result) {{ console.log("CALLBACKE-POST: " + JSON.stringify(result)); }} }}); """ self.browser.execute_script(js) time.sleep(0.2) # print messages for entry in self.browser.get_log('browser'): if entry['level'] == 'INFO': e = entry['message'].find("CALLBACKE") i = entry['message'].find("CALLBACK") if (e != -1): logging.critical(f"ERROR: {entry['message']}\n") return False elif (i != -1): logging.info(f"OK: {entry['message']}\n") return True else: logging.error("WARNING: NO FEEDBACK GIVEN\n") return False return False
script = ''' function post(path, params) { method = "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } ''' script_post = 'post("{}", data={});'.format(action_link, json.dumps(data)) script = script + script_post driver.execute_script(script) driver.save_screenshot('shot.png') driver.quit()