Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Automated Trading using Python
Next article icon

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.

  1. Install Selenium: For controlling browser activities.
  2. Install webdriver_manager: For managing the appropriate browser driver version automatically.
  3. 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:

Step 3: Import Necessary Libraries

Let’s begin by importing the required libraries into your Python script.

Python
fromseleniumimportwebdriverfromselenium.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.

  1. Define the LinkedIn URL and your login credentials.
  2. Use Selenium to open the browser and navigate to LinkedIn's login page.
  3. 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.

  1. Navigate to the LinkedIn search bar.
  2. Input your desired search query (e.g., "Software Engineer").
  3. Automate pressing the "Enter" key to fetch results.
Python
search_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.

  1. Locate the "Connect" buttons on the page.
  2. Click each button and handle any pop-ups.
  3. Add delays between actions to mimic human behavior.
Python
try: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.

Python
fromseleniumimportwebdriverfromwebdriver_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.


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp