Advertisement
Guest User

Untitled

a guest
Oct 30th, 2024
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.22 KB | None | 0 0
  1. import json
  2. from selenium import webdriver
  3. from selenium.webdriver.common.keys import Keys
  4. from selenium.webdriver.common.by import By
  5. from selenium.webdriver.support.ui import WebDriverWait
  6. from selenium.webdriver.support import expected_conditions as EC
  7. from selenium.common.exceptions import NoSuchElementException
  8. from selenium.common.exceptions import ElementClickInterceptedException
  9. from selenium.webdriver.common.action_chains import ActionChains
  10.  
  11. from time import sleep
  12.  
  13. driver = webdriver.Firefox()
  14.  
  15. wait = WebDriverWait(driver, 50)
  16. actions = ActionChains(driver)
  17.  
  18. driver.get('https://twitter.com')
  19.  
  20. scroll_path = "/html/body/div[1]/div/div/div[2]/main/div/div/div/div[1]/div/div[3]/section/div/div"
  21. after_img_path = "div/div/article/div/div/div[2]/div[1]/div/div/div/div/div[2]/div/div[2]/div/a/div[3]/div/div[2]/div/img"
  22. username_path = "div/div/article/div/div/div[2]/div[2]/div[1]/div/div[1]/div/div/div[2]/div/div[1]/a"
  23. clearname_path = "div/div/article/div/div/div[2]/div[2]/div[1]/div/div[1]/div/div/div[1]/div/a/div/div[1]/span/span"
  24. post_id_path = "div/div/article/div/div/div[2]/div[2]/div[1]/div/div[1]/div/div/div[2]/div/div[3]/a"
  25. timestamp_path = "div/div/article/div/div/div[2]/div[2]/div[1]/div/div[1]/div/div/div[2]/div/div[3]/a/time"
  26.  
  27.  
  28. wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div/div/div[2]/main/div/div/div[1]/div[1]/div/div[3]/div[4]/a/div'))).click() # login
  29. wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[4]/label/div'))).click() # username
  30. body = driver.find_element(By.TAG_NAME, "body") # send keystrokes to body
  31. body.send_keys("DiegoCab3110")
  32. body.send_keys(Keys.ENTER)
  33. wait.until(EC.presence_of_element_located((By.XPATH, "/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div/div[3]/div/label/div/div[2]/div[1]/input"))).send_keys("slippy66") # password
  34. driver.find_element(By.XPATH, '/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[2]/div/div[1]/div/div/button').click() # log in
  35.  
  36. wait.until(EC.url_to_be("https://x.com/home"))
  37.  
  38. def navigate(tag):
  39.     driver.get(f"https://x.com/{tag}")
  40.  
  41. def add_to_list(categories: list):
  42.     try:
  43.         wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div[2]/main/div/div/div/div/div/div[3]/div/div/div/div/div[1]/div[2]/button[1]/div'))).click()
  44.         sleep(3)
  45.         wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div[1]/div[2]/div/div/div/div[2]/div/div[3]/div/div/div/a[2]'))).click()
  46.        
  47.         container = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'section.css-175oi2r:nth-child(2) > div:nth-child(2) > div:nth-child(1)')))
  48.         sleep(2)
  49.         container.click()
  50.         contained = container.find_elements(By.XPATH, './div')
  51.        
  52.         selectors = [
  53.             "div[role='dialog'] div[data-testid='listCell']",
  54.             "div[role='dialog'] div[dir='ltr']",
  55.             "//div[@role='dialog']//div[@data-testid='listCell']"
  56.         ]
  57.        
  58.         print('\t' + str(categories))
  59.         found = False
  60.         categories_copy = categories.copy()
  61.  
  62.        
  63.         for selector in selectors:
  64.             try:
  65.                 elements = driver.find_elements(By.CSS_SELECTOR if not selector.startswith("//") else By.XPATH, selector)
  66.                 for element in elements:
  67.                     try:
  68.                         text = element.text.strip()
  69.                         if text.lower() in categories_copy:
  70.                             try:
  71.                                 print(f"\tFound matching list: {text}")
  72.                                 wait.until(EC.element_to_be_clickable(element))
  73.                                
  74.                                 # Enhanced obstruction handling
  75.                                 max_attempts = 10
  76.                                 for attempt in range(max_attempts):
  77.                                     try:
  78.                                         element.click()
  79.                                         break
  80.                                     except ElementClickInterceptedException:
  81.                                         print(f'\tintercepted. removing obstacles (attempt {attempt + 1})...')
  82.                                        
  83.                                         # Get all elements that might be obstructing
  84.                                         script = """
  85.                                        function getObstructingElements(element) {
  86.                                            var rect = element.getBoundingClientRect();
  87.                                            return document.elementsFromPoint(rect.left + rect.width/2, rect.top + rect.height/2)
  88.                                                .filter(e => e !== element && e !== document.documentElement && e !== document.body);
  89.                                        }
  90.                                        var targetElement = arguments[0];
  91.                                        var obstructing = getObstructingElements(targetElement);
  92.                                        obstructing.forEach(function(element) {
  93.                                            if (element.parentNode) {
  94.                                                element.parentNode.removeChild(element);
  95.                                            }
  96.                                        });
  97.                                        """
  98.                                         driver.execute_script(script, element)
  99.                                         sleep(1)
  100.                                
  101.                                 categories_copy.remove(text.lower())
  102.                                 if len(categories_copy) == 0:
  103.                                     found = True
  104.                                     break
  105.                                
  106.                             except Exception as e:
  107.                                 print(f"\tError clicking element: {str(e)}")
  108.                                 continue
  109.                     except Exception as e:
  110.                         print(f"Error checking element: {str(e)}")
  111.                         continue
  112.                 if found:
  113.                     break
  114.             except Exception as e:
  115.                 print(f"Error with selector {selector}: {str(e)}")
  116.                 continue
  117.                
  118.         if not found:
  119.             print(f"Could not find all lists: {categories_copy}")
  120.             return
  121.            
  122.         driver.find_element(By.XPATH, '/html/body/div[1]/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/div/div[3]/button').click()
  123.     except Exception as e:
  124.         print(f"Error in add_to_list: {str(e)}")
  125.  
  126. def unfollow():
  127.     follow_button = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div[2]/main/div/div/div/div/div/div[3]/div/div/div/div/div[1]/div[2]/div[2]/div[1]/button/div/span/span')))
  128.     # /html/body/div[1]/div/div/div[2]/main/div/div/div/div[1]/div/div[3]/div/div/div/div/div[1]/div[2]/div/div[1]/button/div/span/span
  129.     if follow_button.text == "Following":
  130.         #add_to_list('diegos list')        
  131.         follow_button.click()
  132.         confirm_button = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div[2]/button[1]/div/span/span'))).click()
  133.  
  134. if __name__ == '__main__':
  135.     with open('to_use.json', 'r') as file:
  136.         data = json.load(file)
  137.         print(len(data))
  138.         unfollow_flag = False
  139.        
  140.         c = 0
  141.         for key, values in data.items():
  142.             c += 1
  143.             print(str(c).zfill(2) + ': ' + key)
  144.             navigate(key)
  145.             categories = []
  146.             for value in values:
  147.                 if value != 'unfollow':
  148.                     categories.append(value)
  149.                 else:
  150.                     unfollow_flag = True
  151.             if categories:
  152.                 add_to_list(categories)
  153.             if unfollow_flag:
  154.                 sleep(2)
  155.                 unfollow()
  156.                 unfollow_flag = False
  157.              
  158.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement