def reload_webpage(browser): """ Reload the current webpage """ browser.execute_script("location.reload()") # update_activity(browser, state=None) sleep(2) return True
def wait_for_valid_connection(self, username, logger): counter = 0 while True and counter < 10: sirens_wailing, emergency_state = emergency_exit( self, username, logger) if sirens_wailing and emergency_state == "not connected": logger.warning("there is no valid connection") counter += 1 sleep(60) else: break
def wait_port_opening(logger, process_flag): opening_times = 1 while True: port_status = get_port_status() if port_status: logger.info('Port ready!') break else: logger.info('Port not ready, waiting...') sleep(10) opening_times += 1 if opening_times > 6: process_flag = False break return process_flag
def wait_for_valid_authorization(self, username, logger): # save current page current_url = get_current_url(self) # stuck on invalid auth auth_method = "activity counts" counter = 0 while True and counter < 10: login_state = check_authorization(self, username, auth_method, logger) if login_state is False: logger.warning("not logged in") counter += 1 sleep(60) else: break # return to original page web_address_navigator(self, current_url)
def proxy_authentication(browser, logger, proxy_username, proxy_password): """ Authenticate proxy using popup alert window """ # FIXME: https://github.com/SeleniumHQ/selenium/issues/7239 # this feauture is not working anymore due to the Selenium bug report above logger.warn( "Proxy Authentication is not working anymore due to the Selenium bug " "report: https://github.com/SeleniumHQ/selenium/issues/7239") try: # sleep(1) is enough, sleep(2) is to make sure we # give time to the popup windows sleep(2) alert_popup = browser.switch_to_alert() alert_popup.send_keys("{username}{tab}{password}{tab}".format( username=proxy_username, tab=Keys.TAB, password=proxy_password)) alert_popup.accept() except Exception: logger.warn("Unable to proxy authenticate")
def web_address_navigator(browser, link): """Checks and compares current URL of web page and the URL to be navigated and if it is different, it does navigate""" current_url = get_current_url(browser) total_timeouts = 0 page_type = None # file or directory # remove slashes at the end to compare efficiently if current_url is not None and current_url.endswith("/"): current_url = current_url[:-1] if link.endswith("/"): link = link[:-1] page_type = "dir" # slash at the end is a directory new_navigation = current_url != link if current_url is None or new_navigation: link = link + "/" if page_type == "dir" else link # directory links # navigate faster while True: try: browser.get(link) # update server calls # update_activity(browser, state=None) sleep(2) break except TimeoutException as exc: if total_timeouts >= 7: raise TimeoutException( "Retried {} times to GET '{}' webpage " "but failed out of a timeout!\n\t{}".format( total_timeouts, str(link).encode("utf-8"), str(exc).encode("utf-8"), ) ) total_timeouts += 1 sleep(2)
def GetFriendList (self, driver): #driver.get("https://www.facebook.com/david.vendel") sleep(1) driver.find_elements_by_xpath("//*[@class='homeSideNav']//ul/li/a")[0].click() sleep(4) driver.find_element_by_xpath("//*[@id='fbTimelineHeadline']//div/ul/li[3]/a").click() last = -1 for y in range (20): for i in range (35): body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.PAGE_DOWN) sleep(1) linkElements = driver.find_elements_by_xpath("//*[@class='_698']/div/a") friendsUrls = [] for linkEl in linkElements: urlLink = linkEl.get_attribute("href") sep = "?" cleanUrlLink = urlLink.split(sep,1)[0] friendsUrls.append(cleanUrlLink) print ("I have so far ",len(friendsUrls), " friends grabbed. Cycle ",y," out of max 20.") if (last == len(friendsUrls)): print ("No new friends. finishing grabbing") break else: print ("I want more") last = len(friendsUrls) file = open("./profiles/friends.txt","a+") for friend in friendsUrls: file.write(friend) file.write("\n") file.close() print("friends saved in file friends.txt") return friendsUrls
def login_user(browser, logger, conn, proxy_ip, login_url, main_url, account_id, email, username, password, cookies): if not check_browser(browser, logger, proxy_ip): login_state = 2 return login_state web_address_navigator(browser, login_url) current_url = get_current_url(browser) if 'www.pinterest.com' not in current_url: cookies = False cookie_loaded = None login_state = None if cookies: try: for cookie in json.loads(cookies): if "sameSite" in cookie and cookie["sameSite"] == "None": cookie["sameSite"] = "Strict" browser.add_cookie(cookie) cookie_loaded = True logger.info("- Cookie for user '{}' loaded...".format(email)) # force refresh after cookie load or check_authorization() will FAIL reload_webpage(browser) # cookie has been LOADED, so the user SHOULD be logged in login_state = check_authorization(browser, email, "activity counts", logger, False) except: login_state = 0 if login_state == 1 and cookie_loaded: logger.info("Logged in successfully!") login_state = 1 return login_state # if user is still not logged in, then there is an issue with the cookie # so go create a new cookie. if cookie_loaded: logger.info( "- Issue with cookie for user '{}'. Creating new cookie...".format( email)) # Error could be faced due to "<button class="sqdOP L3NKy y3zKF" # type="button"> Cookie could not be loaded" or similar. # Session displayed we are in, but then a failure for the first # `login_elem` like the element is no longer attached to the DOM. # Saw this issue when session hasn't been used for a while; wich means # "expiry" values in cookie are outdated. try: # Since having issues with the cookie a new one can be generated, # if cookie cannot be created or deleted stop execution. logger.info("- Deleting browser cookies...") browser.delete_all_cookies() browser.refresh() time.sleep(random.randint(3, 5)) except Exception as e: # NF: start if isinstance(e, WebDriverException): logger.exception( "Error occurred while deleting cookies from web browser!\n\t{}" .format(str(e).encode("utf-8"))) login_state = 3 return login_state # NF: end web_address_navigator(browser, login_url) input_username_XP = read_xpath(login_user.__name__, "input_username_XP") explicit_wait(browser, logger, "VOEL", [input_username_XP, "XPath"], 35) # user input_username = browser.find_element_by_xpath(input_username_XP) (ActionChains(browser).move_to_element(input_username).click().send_keys( email).perform()) input_password = browser.find_elements_by_xpath( read_xpath(login_user.__name__, "input_password")) if not isinstance(password, str): password = str(password) (ActionChains(browser).move_to_element( input_password[0]).click().send_keys(password).perform()) sleep(1) (ActionChains(browser).move_to_element( input_password[0]).click().send_keys(Keys.ENTER).perform()) sleep(3) # check for wrong username or password message, and show it to the user try: error_alert = browser.find_element_by_xpath( "//*[contains(text(), 'The password you entered is incorrect')]") logger.warn(error_alert.text) login_state = 4 return login_state except NoSuchElementException: pass try: error_alert = browser.find_element_by_xpath( "//*[contains(text(), 'Safe mode alert')]") logger.warn(error_alert.text) login_state = 5 return login_state except NoSuchElementException: pass try: error_alert = browser.find_element_by_xpath( "//*[contains(text(), 'Your account has been suspended.')]") logger.warn(error_alert.text) login_state = 99 return login_state except NoSuchElementException: pass try: error_alert = browser.find_element_by_xpath( "//*[contains(text(), 'Want fresh ideas in your feed')]") logger.warn(error_alert.text) reload_webpage(browser) except NoSuchElementException: pass explicit_wait(browser, logger, "PFL", [], 5) # Check if user is logged-in (If there's two 'nav' elements) nav = browser.find_elements_by_xpath(read_xpath(login_user.__name__, "nav")) if len(nav) == 1: logger.info("Logged in successfully!") login_state = 1 # create cookie for username and save it cookies_list = browser.get_cookies() for cookie in cookies_list: if "sameSite" in cookie and cookie["sameSite"] == "None": cookie["sameSite"] = "Strict" cookies_list = json.dumps(cookies_list) sql = 'UPDATE account SET cookies=%s WHERE id=%s' conn.op_commit(sql, (cookies_list, account_id)) return login_state else: login_state = 0 return login_state
def ProfileLiker (self, driver, profileURL): driver.get(profileURL) print ("liking profile ",profileURL); sleep(2) ############################################################################################## try: profilePhoto = driver.find_element_by_xpath("//*[@class='photoContainer']/div/a/img").click() sleep(2) likeButton = driver.find_element_by_xpath('//*[@id="fbPhotoSnowliftFeedback"]/div/div[1]/div/div/div[2]/div/div/span[1]/div') try: like_el = likeButton.find_element_by_xpath("a[contains(@aria-pressed, 'false')]").click() print("liked") except Exception as err: print("already liked") sleep(1) except: print ("couldng get to profile photo") body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.ESCAPE) sleep(1) ############################################################################################## try: coverPicture = driver.find_element_by_xpath("//*[@id='fbProfileCover']/div/a").click() sleep(2) likeButton = driver.find_element_by_xpath('//*[@id="fbPhotoSnowliftFeedback"]/div/div[1]/div/div/div[2]/div/div/span[1]/div') try: like_el = likeButton.find_element_by_xpath("a[contains(@aria-pressed, 'false')]").click() print("liked") except Exception as err: print("already liked") sleep(1) except: print("couldnt get to cover picture") body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.ESCAPE) sleep(1) ############################################################################################### try: body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.PAGE_DOWN) sleep(1) try: like_el = driver.find_elements_by_xpath("//*[@class='commentable_item']/div/div/div/div/div[2]/div/div/span//a[contains(@aria-pressed, 'false')]")[0].click() print("liked") except Exception as err: print("already liked") print (err) sleep(3) sleep(1) except Exception as err: print (err) print("couldnt get to first post") sleep(3)
def LoginToFb(self): baseUrl = "https://www.facebook.com/" chrome_options = Options() chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("--disable-notifications") print ("\n**********************************************\nWelcome to Facebook mass auto liker bot.\n") try: file = open("./profiles/secret.txt","r") driver = webdriver.Chrome(options=chrome_options) driver.get('http://google.com') lines = file.readlines() fb_username = lines[0] fb_password = lines[1] like_amount = int(lines[2]) file.close() print ("Data loaded.") except: #create directory profiles if not os.path.exists("profiles"): os.makedirs("profiles") print ("To connect to Facebook, please write your facebook login info here. This will be only stored locally in your PC in secret.txt file and this program doesn't send nothing elsewhere.") sleep(1) fb_username = input("\nFacebook username ... ") # Python 3 sleep(0.3) fb_password = input("Facebook password ... ") # Python 3 sleep(0.5) print ("\nThis information will be stored in /profiles/secret.txt file. If you want to change them, delete that file and run this program again.") sleep(0.5) like_amount = int(input("\nhow many likes to give? ... ")) # Python 3 file = open("./profiles/secret.txt","w") file.write(fb_username) file.write("\n") file.write(fb_password) file.write("\n") file.write(str(like_amount)) file.write("\n") file.close() print ("\nAll great!\nI won't ask this information again. You can change them in file secret.txt in /profiles/ directory, or delete that file and run me again.") sleep(0.5) driver = webdriver.Chrome(options=chrome_options) try: cookies = pickle.load(open("fba-cook.pkl", "rb")) for cookie in cookies: driver.add_cookie(cookie) print ("added cookies") except Exception as err: print (err) print ("not added cookies") driver.get(baseUrl) sleep(0.5) driver.set_window_size(1111, 1000) try: sleep(0.5) email = driver.find_element_by_xpath("//*[@id='email']") password = driver.find_element_by_xpath("//*[@id='pass']") fb_username = fb_username.replace("\n","") email.send_keys(fb_username) sleep(0.9) password.send_keys(fb_password) sleep(0.25) try: driver.find_element_by_xpath("//input[@data-testid='royal_login_button']").click() except: pass sleep(0.5) sleep(0.5) except: pass pickle.dump(driver.get_cookies() , open("fba-cook.pkl","wb")) return driver
def AutoLiker(self, driver): file = open("./profiles/secret.txt","r") lines = file.readlines() like_amount = int(lines[2]) file.close() liked = 0 tre = 0 #error counter - if error 3x in a row, will refresh page i = 0 #index of like element in newsfeed body_elem = driver.find_element_by_tag_name('body') print ("Going to like",like_amount,"photos.") while liked<=like_amount: print ("Liked", liked,"/",like_amount) try: if i>25: print ("Let's reload") driver.get("http://www.facebook.com") sleep(5) i = 0 likes = driver.find_elements_by_xpath("//a[contains(@aria-pressed, 'false')]") print ("There are ",len(likes), " on this page.") if (random.randint(1,100)<65): print ("liking") try: likes[i].click() liked +=1 n = random.randint(1,300) n = n/100 print (n, 3**n) sleep(3**n ) except: print ("cant click") sleep(1) i+=1 body_elem.send_keys(Keys.ESCAPE) sleep(0.1) body_elem.send_keys(Keys.DOWN) sleep(0.1) body_elem.send_keys(Keys.DOWN) sleep(0.1) body_elem.send_keys(Keys.DOWN) sleep(0.1) body_elem.send_keys(Keys.DOWN) sleep(0.1) body_elem.send_keys(Keys.DOWN) else: print ("skipping") i+=1 ''' try: like_el = likes[i] if len(like_el)>0: print ("Already liked") else: likes[i].click() liked +=1 except Exception as e: #print (e) pass ''' try: discover_el = driver.find_elements_by_xpath('//*[@id="appsNav"]/h4') except: print ("Couldn't locate the left panel placeholder. Terminating.") sleep(1) break discover_el_location = discover_el[0].location #print (discover_el_location) location = likes[i].location size = likes[i].size #print(location['y']) #print(size) body_elem.send_keys(Keys.DOWN) body_elem.send_keys(Keys.DOWN) body_elem = driver.find_element_by_tag_name('body') while discover_el_location['y']+80<location['y']: if discover_el_location['y']+2000<location['y']: print ("Things are out of order, either you scrolled up or window width is too small. Terminating") sleep(1) #print ("i is",i) discover_el = driver.find_elements_by_xpath('//*[@id="appsNav"]/h4') discover_el_location = discover_el[0].location location = likes[i].location size = likes[i].size body_elem.send_keys(Keys.DOWN) if location['y'] > 20000: #will refresh page if scrolled too deep print ("Feed too deep, refreshing") driver.get("http://www.facebook.com") n = random.randint (200,1100) print ("sleeping for ",n) sleep(n) i =-1 sleep(scroll_speed) #driver.get("https://www.facebook.com/") except Exception as e: print (e) if tre < 3: print ("Refreshing in.. :", 4-tre) tre+=1 sleep(1) body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.DOWN) body_elem.send_keys(Keys.DOWN) sleep(1) else: sleeptime = random.randint(50,500) print ("Things are bad. refreshing.\nSleeping for ",sleeptime) tre=0 driver.get("http://www.facebook.com") sleep(sleeptime) i = 0
file.write("\n") file.close() print("friends saved in file friends.txt") return friendsUrls print("*"*54) print ("*"*11,"WELCOME AT FACEBOOK MASS LIKER","*"*11) print("*"*54) session = FacebookLiker() driver = session.LoginToFb() session.AutoLiker(driver) friendsArray = ["https://www.facebook.com/fiama.canzani","https://www.facebook.com/luboszima", "https://www.facebook.com/amaiacanzani"] #friendsArray = session.GetFriendList (driver) for friend in friendsArray: session.ProfileLiker(driver, friend) file = open("./profiles/alreadyLiked.txt","w") file.write(friend) file.write("\n") file.close() sleep(1) print ("Finished.") sleep(3) driver.close()
driver.get(post_url) engagement_div = driver.find_element_by_css_selector("a[href*='/ufi/reaction']") driver.execute_script("arguments[0].click();", engagement_div) # switch to all engagement - not working engagement_all = driver.find_element_by_css_selector("a[tabindex*='-1']") driver.execute_script("arguments[0].click();", engagement_div) # click see more until there no such option print("Loading all the users.") while True: try: viewMoreButton = driver.find_element_by_css_selector("a[href*='/ufi/reaction/profile/browser/fetch']") driver.execute_script("arguments[0].click();", viewMoreButton) sleep(2) except NoSuchElementException: break # invite users print("Inviting the users.") users = driver.find_elements_by_css_selector("a[ajaxify*='/pages/post_like_invite/send/']") invitedUsers = 0 for i in users: user = driver.find_element_by_css_selector("a[ajaxify*='/pages/post_like_invite/send/']") driver.execute_script("arguments[0].click();", user) invitedUsers = invitedUsers + 1 sleep(1) print('My job is done here. I have invited: ' + str(invitedUsers))
def AutoLiker(self): baseUrl = "https://www.facebook.com/jhony.sahu" chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications": 2} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome('.chromedriver', chrome_options=chrome_options) driver.get('http://google.com') driver.get(baseUrl) sleep(0.5) driver.set_window_size(1111, 1000) sleep(0.5) email = driver.find_element(By.XPATH, "//*[@id='email']") password = driver.find_element(By.XPATH, "//*[@id='pass']") email.send_keys(fb_username) sleep(0.1) password.send_keys(fb_password) sleep(0.2) driver.find_element(By.XPATH, "//input[@data-testid='royal_login_button']").click() sleep(1) liked = 0 tre = 0 # error counter - if error 3x in a row, will refresh page i = -1 # index of like element in newsfeed body_elem = driver.find_element_by_tag_name('body') print("Going to like", like_amount, "photos.") while liked < like_amount: print("Liked", liked, "/", like_amount) try: i += 1 likes = driver.find_elements_by_xpath("//div[contains(@class, '_khz') and contains(@class, '_4sz1')]") try: like_el = likes[i].find_elements_by_xpath("a[contains(@aria-pressed, 'true')]") if len(like_el) > 0: print("Already liked") else: likes[i].click() liked += 1 except Exception as e: # print (e) pass try: discover_el = driver.find_elements_by_xpath('//*[@id="appsNav"]/h4') except: print("Couldn't locate the left panel placeholder. Terminating.") sleep(1) break discover_el_location = discover_el[0].location # print (discover_el_location) location = likes[i].location size = likes[i].size # print(location['y']) # print(size) body_elem.send_keys(Keys.DOWN) body_elem.send_keys(Keys.DOWN) body_elem = driver.find_element_by_tag_name('body') while discover_el_location['y'] + 80 < location['y']: if discover_el_location['y'] + 2000 < location['y']: print( "Things are out of order, either you scrolled up or window width is too small. Terminating") sleep(1) return # print ("i is",i) discover_el = driver.find_elements_by_xpath('//*[@id="appsNav"]/h4') discover_el_location = discover_el[0].location location = likes[i].location size = likes[i].size body_elem.send_keys(Keys.DOWN) if location['y'] > 20000: # will refresh page if scrolled too deep print("Feed too deep, refreshing") driver.get("http://www.facebook.com") n = random.randint(2, 11) print("sleeping for ", n) sleep(n) i = -1 sleep(scroll_speed) # driver.get("https://www.facebook.com/") except Exception as e: print(e) if tre < 3: print("Refreshing in.. :", 4 - tre) tre += 1 sleep(1) body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.DOWN) body_elem.send_keys(Keys.DOWN) sleep(1) else: print("Things are bad. refreshing") tre = 0 driver.get("http://www.facebook.com") sleep(5) i = 0
# driver.get("https://www.facebook.com/") except Exception as e: print(e) if tre < 3: print("Refreshing in.. :", 4 - tre) tre += 1 sleep(1) body_elem = driver.find_element_by_tag_name('body') body_elem.send_keys(Keys.DOWN) body_elem.send_keys(Keys.DOWN) sleep(1) else: print("Things are bad. refreshing") tre = 0 driver.get("http://www.facebook.com") sleep(5) i = 0 print("*" * 54) print("*" * 11, "WELCOME AT FACEBOOK MASS LIKER", "*" * 11) print("*" * 54) session = FacebookLiker() session.AutoLiker() sleep(5)