from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

# driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver",
driver = webdriver.Chrome(
# driver = webdriver.Firefox(    
# driver = webdriver.PhantomJS(
    service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any'])

# driver.maximize_window()

driver.get("https://i...content-available-to-author-only...m.com/accounts/login")
username = driver.find_element_by_name("username")
password = driver.find_element_by_name("password")

username1 = 'rbn999'  # change it!
password1 = '12345678!@##$$%^%^&&*(*()' # change it!

username.send_keys(username1)
password.send_keys(password1)

submit_button = driver.find_element_by_css_selector(
    '#react-root > div > article > div > div:nth-child(1) > div > form > span > button')
submit_button.click()

sleep(2)

toVisit = username1

link = 'https://w...content-available-to-author-only...m.com/%s/' % (toVisit)
driver.get(link)

driver.implicitly_wait(2)
following = driver.find_element_by_xpath("//a[@href='/%s/following/']/span" % (toVisit))
total_following = int(following.text)

print("total no. of users following: %d" % (total_following))

following.click()

def recursiveFunc(SleepSeconds):
    try:
        loaded_following = driver.find_elements_by_xpath("//ul[@class='_539vh _4j13h']/li")
        loaded_till_now = len(loaded_following)

        while(loaded_till_now<total_following):
            print(loaded_following[loaded_till_now-1])
            print("following users loaded till now: %d" % (loaded_till_now))
            loaded_following[loaded_till_now-1].location_once_scrolled_into_view
            # driver.execute_script("arguments[0].focus();", loaded_following[loaded_till_now-1])
            driver.find_element_by_tag_name('body').send_keys(Keys.END) # triggers AJAX request to load more users. observed that loading 10 users at a time.

            print("SleepSeconds = %d" % (SleepSeconds))            
            sleep(SleepSeconds) # tried without sleep but throws StaleElementReferenceException. As it takes time to get the response and update the DOM
            
            loaded_following = driver.find_elements_by_xpath("//ul[@class='_539vh _4j13h']/li")
            loaded_till_now = len(loaded_following)
    except:
        recursiveFunc(SleepSeconds+1)

recursiveFunc(1)

for ns in driver.find_elements_by_class_name("_6jvgy"):
    try:
        ns.find_element_by_class_name("_r4e4p").click() # unFollow button!!!

        # time.sleep(2) # the same as without sleep  
        # driver.implicitly_wait(1)

        unfollow_nick = ns.find_element_by_class_name("notranslate").get_attribute("title")
        print(unfollow_nick) # now: prints all, but really unfollow only 15. 

        # c+=1
        # if c%4 == 0:
        #     time.sleep(10) # seconds; unfollow 11 people instead of 15 or all; worse

    except:
        pass

driver.quit()
