Automating LinkedIn connections using Python involves creating a script that navigates LinkedIn, finds users based on specific criteria (e.g., job title, company, or location), and sends personalized connection requests. In this article, we will walk you through the process, using Selenium for web automation. This automation simplifies networking while maintaining a personal touch.
Step 1: Install Required Libraries
We need a few libraries to perform web automation and handle web elements effectively.
- Install Selenium: For controlling browser activities.
- Install webdriver_manager: For managing the appropriate browser driver version automatically.
- Install time and other standard libraries: For adding delays and managing timing during automation.
pip install selenium webdriver-manager
Step 2: Set Up the Environment
To automate LinkedIn connections, you’ll need:
- A LinkedIn account.
- Installed Chrome or another browser.
- Downloaded and installed the corresponding web driver (e.g., ChromeDriver for Chrome).
Step 3: Import Necessary Libraries
Let’s begin by importing the required libraries into your Python script.
Pythonfromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.chrome.serviceimportServicefromwebdriver_manager.chromeimportChromeDriverManagerimporttime
Step 4: Log in to LinkedIn
We will automate the login process to access LinkedIn.
- Define the LinkedIn URL and your login credentials.
- Use Selenium to open the browser and navigate to LinkedIn's login page.
- Enter your username and password, then click the "Sign in" button.
Python# Set up the browserdriver=webdriver.Chrome(service=Service(ChromeDriverManager().install()))driver.get("https://www.linkedin.com/login")# Enter login credentialsusername=driver.find_element(By.ID,"username")password=driver.find_element(By.ID,"password")username.send_keys("your_email@example.com")password.send_keys("your_password")# Click login buttonlogin_button=driver.find_element(By.XPATH,"//button[@type='submit']")login_button.click()time.sleep(3)# Wait for the page to load
Step 5: Search for Profiles
Search for users based on specific criteria like job titles or companies.
- Navigate to the LinkedIn search bar.
- Input your desired search query (e.g., "Software Engineer").
- Automate pressing the "Enter" key to fetch results.
Pythonsearch_box=driver.find_element(By.CSS_SELECTOR,".search-global-typeahead__input.search-global-typeahead__input--ellipsis")search_box.send_keys("Software Engineer")# Replace with your search querysearch_box.send_keys(Keys.RETURN)time.sleep(5)
Step 6: Send Connection Requests
Now we’ll loop through the profiles and send connection requests.
- Locate the "Connect" buttons on the page.
- Click each button and handle any pop-ups.
- Add delays between actions to mimic human behavior.
Pythontry:whileTrue:# Loop to process profiles on the current page# Scroll to load profiles dynamicallydriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")time.sleep(3)# Wait for new profiles to load# Find all "Connect" buttonsconnect_buttons=driver.find_elements(By.XPATH,"//button[.//span[contains(@class, 'artdeco-button__text') and text()='Connect']]")ifnotconnect_buttons:print("No 'Connect' buttons found on the current page.")break# Exit the loop if no buttons are foundforbuttoninconnect_buttons:try:# Scroll to the "Connect" button to bring it into viewdriver.execute_script("arguments[0].scrollIntoView(true);",button)time.sleep(1)# Allow time for scrolling# Try normal clicktry:button.click()except:# Fallback to JavaScript click if intercepteddriver.execute_script("arguments[0].click();",button)time.sleep(2)# Allow time for the pop-up to load# Click the "Send without a note" button in the pop-uptry:send_without_note_button=WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.XPATH,"//button[.//span[contains(@class, 'artdeco-button__text') and text()='Send without a note']]")))send_without_note_button.click()print("Connection request sent successfully.")time.sleep(2)exceptExceptionassend_error:print(f"Error finding 'Send without a note' button:{send_error}")exceptExceptionasbutton_error:print(f"Error clicking 'Connect' button:{button_error}")exceptKeyboardInterrupt:print("Script stopped by user.")
Step 7: Log Out and Close the Browser
Once all actions are completed, log out and close the browser to end the session.
Python# Log out (optional)driver.get("https://www.linkedin.com/login?session_redirect=https%3A%2F%2Fwww.linkedin.com%2Fm%2Flogout%2F")# Close the browserdriver.quit()
Step 8: Full Code Implementation
Below is the complete Python script for automating LinkedIn connections. You can run this code after ensuring you have set up everything correctly.
Pythonfromseleniumimportwebdriverfromwebdriver_manager.chromeimportChromeDriverManagerfromselenium.webdriver.chrome.serviceimportServicefromselenium.webdriver.common.byimportByfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.action_chainsimportActionChainsfromselenium.webdriver.chrome.serviceimportServicefromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECfromwebdriver_manager.chromeimportChromeDriverManagerimporttime# Step 1: Set up the browserdriver=webdriver.Chrome(service=Service(ChromeDriverManager().install()))driver.get("https://www.linkedin.com/login")# Step 2: Log in to LinkedInusername=driver.find_element(By.ID,"username")password=driver.find_element(By.ID,"password")username.send_keys("Enter your linkedin email")# Replace with your LinkedIn emailpassword.send_keys("Enter your password here")# Replace with your LinkedIn password# Click login buttonlogin_button=driver.find_element(By.XPATH,"//button[@type='submit']")login_button.click()time.sleep(3)# Step 3: Search for profiles using the correct class name for search boxsearch_box=driver.find_element(By.CSS_SELECTOR,".search-global-typeahead__input.search-global-typeahead__input--ellipsis")search_box.send_keys("Software Engineer")# Replace with your search querysearch_box.send_keys(Keys.RETURN)time.sleep(5)# Step 4: Navigate to the "People" tab using Explicit Waittry:# Wait for the "People" button to be clickablepeople_tab=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(., 'People')]")))people_tab.click()print("Navigated to the 'People' section successfully.")time.sleep(5)exceptExceptionase:print(f"Error navigating to the 'People' section:{e}")driver.quit()exit()# Step 5: Send connection requeststry:whileTrue:# Loop to process profiles on the current page# Scroll to load profiles dynamicallydriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")time.sleep(3)# Wait for new profiles to load# Find all "Connect" buttonsconnect_buttons=driver.find_elements(By.XPATH,"//button[.//span[contains(@class, 'artdeco-button__text') and text()='Connect']]")ifnotconnect_buttons:print("No 'Connect' buttons found on the current page.")break# Exit the loop if no buttons are foundforbuttoninconnect_buttons:try:# Scroll to the "Connect" button to bring it into viewdriver.execute_script("arguments[0].scrollIntoView(true);",button)time.sleep(1)# Allow time for scrolling# Try normal clicktry:button.click()except:# Fallback to JavaScript click if intercepteddriver.execute_script("arguments[0].click();",button)time.sleep(2)# Allow time for the pop-up to load# Click the "Send without a note" button in the pop-uptry:send_without_note_button=WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.XPATH,"//button[.//span[contains(@class, 'artdeco-button__text') and text()='Send without a note']]")))send_without_note_button.click()print("Connection request sent successfully.")time.sleep(2)exceptExceptionassend_error:print(f"Error finding 'Send without a note' button:{send_error}")exceptExceptionasbutton_error:print(f"Error clicking 'Connect' button:{button_error}")exceptKeyboardInterrupt:print("Script stopped by user.")
Output:
Navigated to the 'People' section successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
Connection request sent successfully.
No 'Connect' buttons found on the current page.
The console will show something like this while you can watch all the automated connection request on the browser tab that opened automatically.