import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
--- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_links.xlsx"
SCROLL_PAUSE_TIME = 10 # Increased wait time for better loading
TARGET_LINKS = 200 # Minimum number of links to collect
MAX_SCROLLS = 50 # Maximum number of scrolls to prevent infinite loops
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
code
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def scrape_post_links(driver, url):
"""Scrolls dynamically until target number of links is reached."""
print(f"Navigating to company page: {url}")
driver.get(url)
time.sleep(10) # Longer initial load time
code
post_links = set()
scroll_count = 0
consecutive_no_new = 0
max_consecutive = 5 # Allow more attempts before stopping
print(f"Starting collection (target: {TARGET_LINKS} links)...")
while len(post_links) < TARGET_LINKS and scroll_count < MAX_SCROLLS:
# Get current posts
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_links)
# Process posts
for post in current_posts:
try:
urn = post.get_attribute("data-urn")
if urn:
full_link = f"https://www.linkedin.com/feed/update/{urn}"
post_links.add(full_link)
except Exception as e:
print(f"Error processing post: {e}")
# Check for progress
new_count = len(post_links)
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new posts. Total: {new_count}/{TARGET_LINKS}")
# Scroll down
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
# Wait for content to load
time.sleep(SCROLL_PAUSE_TIME)
# Check stop conditions
if consecutive_no_new >= max_consecutive:
print(f"Stopping - No new posts for {max_consecutive} consecutive scrolls")
break
print(f"\nFinal count: {len(post_links)} unique posts found")
return list(post_links)
def save_to_excel(links, filename):
"""Saves links to Excel file."""
if not links:
print("No links found to save")
return
if name == "main":
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
code
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10)
try:
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Handle security check
if "feed" not in driver.current_url and "login" in driver.current_url:
print("\nPlease complete security check in browser window")
input("Press Enter after logging in manually...")
all_links = scrape_post_links(driver, COMPANY_URL)
save_to_excel(all_links, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
ok, now I need a code that will fetch the body text of the post from each of the posts, the code first need to open the post and fetch the body text of the post
Assistant
Fetching Post Body Text from LinkedIn Posts
To fetch the body text of the posts from the links collected earlier, we'll create a new function fetch_post_body_text that will navigate to each post link, extract the body text, and return it.
Code
python
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
def fetch_post_body_text(driver, post_link):
"""Fetches the body text of a LinkedIn post."""
try:
driver.get(post_link)
time.sleep(5) # Wait for the post to load
# Try to find the post body text
try:
post_body = driver.find_element(By.CSS_SELECTOR, "div.update-components-text")
return post_body.text.strip()
except NoSuchElementException:
print(f"Could not find post body for {post_link}")
return None
except Exception as e:
print(f"Error fetching post body for {post_link}: {e}")
return None
def fetch_all_post_body_text(driver, post_links):
"""Fetches the body text for all posts."""
post_body_texts = []
for post_link in post_links:
print(f"Fetching post body for {post_link}...")
post_body_text = fetch_post_body_text(driver, post_link)
post_body_texts.append(post_body_text)
time.sleep(2) # Wait before fetching the next post
return post_body_texts
def save_to_excel(post_links, post_body_texts, filename):
"""Saves post links and body texts to Excel file."""
if not post_links or not post_body_texts:
print("No data found to save")
return
print(f"Saving {len(post_links)} posts to {filename}...")
import pandas as pd
df = pd.DataFrame({
'Post URL': post_links,
'Post Body Text': post_body_texts
})
df.to_excel(filename, index=False)
print("File saved successfully.")
if __name__ == "__main__":
# Load the post links from the Excel file
import pandas as pd
post_links_df = pd.read_excel(OUTPUT_FILE)
post_links = post_links_df['Post URL'].tolist()
# Create a new Chrome driver instance
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10)
try:
# Login to LinkedIn (you can reuse the login function from the previous code)
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Fetch post body texts
post_body_texts = fetch_all_post_body_text(driver, post_links)
# Save post links and body texts to Excel
save_to_excel(post_links, post_body_texts, "linkedin_post_data.xlsx")
finally:
print("Closing browser")
driver.quit()
User
I don't want to fetch the links but just the body texts
Assistant
Fetching Post Body Text from LinkedIn Posts
To fetch the body text of the posts from the links collected earlier, we'll create a new function fetch_post_body_text that will navigate to each post link, extract the body text, and return it.
Code
python
User
/Users/arturwillonski/Documents/scrapper/venv/bin/python /Users/arturwillonski/Documents/scrapper/linkedin_scraper.py
venvarturwillonski@Mac scrapper % /Users/arturwillonski/Documents/scrapp
er/venv/bin/python /Users/arturwillonski/Documents/scrapper/linkedin_scr
aper.py
Traceback (most recent call last):
File "/Users/arturwillonski/Documents/scrapper/linkedin_scraper.py", line 74, in
post_links_df = pd.read_excel("linkedin_post_links.xlsx")
File "/Users/arturwillonski/Documents/scrapper/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 495, in read_excel
io = ExcelFile(
io,
...<2 lines>...
engine_kwargs=engine_kwargs,
)
File "/Users/arturwillonski/Documents/scrapper/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 1550, in init
ext = inspect_excel_format(
content_or_path=path_or_buffer, storage_options=storage_options
)
File "/Users/arturwillonski/Documents/scrapper/venv/lib/python3.13/site-packages/pandas/io/excel/_base.py", line 1402, in inspect_excel_format
with get_handle(
~~~~~~~~~~^
content_or_path, "rb", storage_options=storage_options, is_text=False
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
) as handle:
^
File "/Users/arturwillonski/Documents/scrapper/venv/lib/python3.13/site-packages/pandas/io/common.py", line 882, in get_handle
handle = open(handle, ioargs.mode)
FileNotFoundError: [Errno 2] No such file or directory: 'linkedin_post_links.xlsx'
venvarturwillonski@Mac scrapper %
Assistant
The error message indicates that the file "linkedin_post_links.xlsx" is not found in the current working directory. This file is supposed to contain the post links that were scraped earlier.
To fix this issue, you need to make sure that the file "linkedin_post_links.xlsx" exists in the same directory as your Python script, or provide the full path to the file.
Here are a few possible solutions:
Run the post link scraper script first: If you haven't already, run the script that scrapes the post links and saves them to an Excel file. This will create the "linkedin_post_links.xlsx" file.
Provide the full path to the file: If the "linkedin_post_links.xlsx" file is located in a different directory, you can provide the full path to the file in the pd.read_excel() function.
Change the current working directory: You can change the current working directory to the location where the "linkedin_post_links.xlsx" file is stored.
python
import os
os.chdir("/path/to/directory")
post_links_df = pd.read_excel("linkedin_post_links.xlsx")
Handle the FileNotFoundError exception: You can add a try-except block to handle the FileNotFoundError exception and provide a meaningful error message.
python
try:
post_links_df = pd.read_excel("linkedin_post_links.xlsx")
except FileNotFoundError:
print("Error: The file 'linkedin_post_links.xlsx' was not found. Please make sure it exists in the current working directory or provide the full path to the file.")
exit()
User
give me a fixed code
Assistant
Fixed Code
python
User
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # Import for Keys.RETURN
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
--- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_texts.xlsx" # File to save body texts
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of posts to collect texts from
MAX_SCROLLS = 50 # Maximum number of scrolls
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
code
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN) # Submit the form
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def scrape_post_texts(driver, url):
"""Scrolls dynamically and extracts body texts from posts."""
print(f"Navigating to company page: {url}")
driver.get(url)
time.sleep(10) # Wait for initial load
code
Assistant
Modified Code
python
User
edit the code so that only unique posts are fetched
Assistant
Modified Code
python
User
could you update the code so that the posts are fetched in the file from newest to the oldest?
Updated the COMPANY_URL to include the sortBy=RECENCY parameter, which sorts the posts by recency (newest to oldest).
Usage
Run the script to fetch the post details (URN, link, and text) and save them to an Excel file named "linkedin_post_details.xlsx". The script will fetch the posts in the order of newest to oldest.
By adding sortBy=RECENCY to the URL, LinkedIn will return the posts in the order of newest to oldest. This should ensure that the script fetches the posts in the desired order.
The fetch_post_body_text function navigates to a post link, waits for the post to load, and extracts the body text using a CSS selector.
The fetch_all_post_body_text function fetches the body text for all posts by iterating over the post links.
The save_to_excel function saves the post links and body texts to an Excel file.
Usage
Run the code to fetch the post body texts and save them to an Excel file named "linkedin_post_data.xlsx".
Make sure to replace OUTPUT_FILE with the actual file name used in the previous code.
Note that this code assumes you have the selenium, webdriver-manager, and pandas libraries installed. If not, you can install them using pip: pip install selenium webdriver-manager pandas.
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import getpass
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def fetch_post_body_text(driver, post_link):
"""Fetches the body text of a LinkedIn post."""
try:
driver.get(post_link)
time.sleep(5) # Wait for the post to load
# Try to find the post body text
try:
post_body = driver.find_element(By.CSS_SELECTOR, "div.update-components-text")
return post_body.text.strip()
except NoSuchElementException:
print(f"Could not find post body for {post_link}")
return None
except Exception as e:
print(f"Error fetching post body for {post_link}: {e}")
return None
def fetch_all_post_body_text(driver, post_links):
"""Fetches the body text for all posts."""
post_body_texts = []
for post_link in post_links:
print(f"Fetching post body for {post_link}...")
post_body_text = fetch_post_body_text(driver, post_link)
post_body_texts.append(post_body_text)
time.sleep(2) # Wait before fetching the next post
return post_body_texts
def save_to_excel(post_body_texts, filename):
"""Saves post body texts to Excel file."""
if not post_body_texts:
print("No data found to save")
return
print(f"Saving {len(post_body_texts)} posts to {filename}...")
df = pd.DataFrame({
'Post Body Text': post_body_texts
})
df.to_excel(filename, index=False)
print("File saved successfully.")
if __name__ == "__main__":
# Load the post links from the Excel file
post_links_df = pd.read_excel("linkedin_post_links.xlsx")
post_links = post_links_df['Post URL'].tolist()
# Create a new Chrome driver instance
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10)
try:
# Login to LinkedIn
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Fetch post body texts
post_body_texts = fetch_all_post_body_text(driver, post_links)
# Save post body texts to Excel
save_to_excel(post_body_texts, "linkedin_post_body_texts.xlsx")
finally:
print("Closing browser")
driver.quit()
Explanation
The fetch_post_body_text function navigates to a post link, waits for the post to load, and extracts the body text using a CSS selector.
The fetch_all_post_body_text function fetches the body text for all posts by iterating over the post links.
The save_to_excel function saves the post body texts to an Excel file.
Usage
Run the code to fetch the post body texts and save them to an Excel file named "linkedin_post_body_texts.xlsx".
Make sure to replace "linkedin_post_links.xlsx" with the actual file name used to store the post links.
Note that this code assumes you have the selenium, webdriver-manager, and pandas libraries installed. If not, you can install them using pip: pip install selenium webdriver-manager pandas.
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import getpass
import os
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def fetch_post_body_text(driver, post_link):
"""Fetches the body text of a LinkedIn post."""
try:
driver.get(post_link)
time.sleep(5) # Wait for the post to load
# Try to find the post body text
try:
post_body = driver.find_element(By.CSS_SELECTOR, "div.update-components-text")
return post_body.text.strip()
except NoSuchElementException:
print(f"Could not find post body for {post_link}")
return None
except Exception as e:
print(f"Error fetching post body for {post_link}: {e}")
return None
def fetch_all_post_body_text(driver, post_links):
"""Fetches the body text for all posts."""
post_body_texts = []
for post_link in post_links:
print(f"Fetching post body for {post_link}...")
post_body_text = fetch_post_body_text(driver, post_link)
post_body_texts.append(post_body_text)
time.sleep(2) # Wait before fetching the next post
return post_body_texts
def save_to_excel(post_body_texts, filename):
"""Saves post body texts to Excel file."""
if not post_body_texts:
print("No data found to save")
return
print(f"Saving {len(post_body_texts)} posts to {filename}...")
df = pd.DataFrame({
'Post Body Text': post_body_texts
})
df.to_excel(filename, index=False)
print("File saved successfully.")
def load_post_links(filename):
try:
return pd.read_excel(filename)['Post URL'].tolist()
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found. Please make sure it exists in the current working directory or provide the full path to the file.")
exit()
if __name__ == "__main__":
# Load the post links from the Excel file
post_links_filename = "linkedin_post_links.xlsx"
post_links = load_post_links(post_links_filename)
# Create a new Chrome driver instance
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10)
try:
# Login to LinkedIn
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Fetch post body texts
post_body_texts = fetch_all_post_body_text(driver, post_links)
# Save post body texts to Excel
save_to_excel(post_body_texts, "linkedin_post_body_texts.xlsx")
finally:
print("Closing browser")
driver.quit()
Changes Made
Added a load_post_links function to handle loading post links from an Excel file.
Added a try-except block to handle the FileNotFoundError exception when loading post links.
Provided a meaningful error message when the file is not found.
Usage
Make sure the "linkedin_post_links.xlsx" file exists in the same directory as your Python script.
Run the script to fetch the post body texts and save them to an Excel file named "linkedin_post_body_texts.xlsx".
post_texts = [] # List to store results: [{'Post URN': urn, 'Body Text': text}]
scroll_count = 0
consecutive_no_new = 0
max_consecutive = 5 # Stop if no new posts for this many scrolls
print(f"Starting collection (target: {TARGET_POSTS} posts)...")
while len(post_texts) < TARGET_POSTS and scroll_count < MAX_SCROLLS:
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_texts)
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference
if urn:
# Locate and extract the body text (adjust selector if needed)
text_element = post.find_element(By.CSS_SELECTOR, "div.update-components-text") # Example selector
body_text = text_element.text # Extract text
post_texts.append({'Post URN': urn, 'Body Text': body_text}) # Store with URN
except NoSuchElementException:
print("Text element not found for a post. Skipping...")
# Optionally add: post_texts.append({'Post URN': 'Unknown', 'Body Text': 'N/A'})
except StaleElementReferenceException:
print("Stale element encountered; skipping.")
continue # Skip if element is stale
new_count = len(post_texts)
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new posts. Total: {new_count}/{TARGET_POSTS}")
# Scroll down to load more
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
time.sleep(SCROLL_PAUSE_TIME) # Wait for content to load
if consecutive_no_new >= max_consecutive:
print(f"Stopping - No new posts for {max_consecutive} consecutive scrolls")
break
print(f"\nFinal count: {len(post_texts)} unique posts' texts extracted")
return post_texts # Return list of dictionaries
def save_to_excel(post_details, filename):
"""Saves post details to Excel file."""
if not post_details:
print("No post texts found to save")
return
code
print(f"Saving {len(post_details)} post texts to {filename}...")
df = pd.DataFrame(post_details, columns=['Post URN', 'Body Text']) # Columns for URN and text
df.to_excel(filename, index=False)
print("File saved successfully.")
if name == "main":
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
code
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10) # Implicit wait for elements
try:
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Handle security check
if "feed" not in driver.current_url and "login" in driver.current_url:
print("\nPlease complete security check in browser window")
input("Press Enter after logging in manually...")
post_details = scrape_post_texts(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
now I need to fetch the body text of the post and the link to that post, can you edit the code like this?
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # Import for Keys.RETURN
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
# --- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_details.xlsx" # File to save post details
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of posts to collect details from
MAX_SCROLLS = 50 # Maximum number of scrolls
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN) # Submit the form
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def scrape_post_details(driver, url):
"""Scrolls dynamically and extracts post details (URN, body text, and link)."""
print(f"Navigating to company page: {url}")
driver.get(url)
time.sleep(10) # Wait for initial load
post_details = [] # List to store results: [{'Post URN': urn, 'Post Link': link, 'Body Text': text}]
scroll_count = 0
consecutive_no_new = 0
max_consecutive = 5 # Stop if no new posts for this many scrolls
print(f"Starting collection (target: {TARGET_POSTS} posts)...")
while len(post_details) < TARGET_POSTS and scroll_count < MAX_SCROLLS:
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_details)
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference
if urn:
post_link = f"https://www.linkedin.com/feed/update/{urn}" # Construct post link
# Locate and extract the body text (adjust selector if needed)
text_element = post.find_element(By.CSS_SELECTOR, "div.update-components-text") # Example selector
body_text = text_element.text # Extract text
post_details.append({'Post URN': urn, 'Post Link': post_link, 'Body Text': body_text}) # Store with URN, link, and text
except NoSuchElementException:
print("Text element not found for a post. Skipping...")
# Optionally add: post_details.append({'Post URN': 'Unknown', 'Post Link': 'N/A', 'Body Text': 'N/A'})
except StaleElementReferenceException:
print("Stale element encountered; skipping.")
continue # Skip if element is stale
new_count = len(post_details)
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new posts. Total: {new_count}/{TARGET_POSTS}")
# Scroll down to load more
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
time.sleep(SCROLL_PAUSE_TIME) # Wait for content to load
if consecutive_no_new >= max_consecutive:
print(f"Stopping - No new posts for {max_consecutive} consecutive scrolls")
break
print(f"\nFinal count: {len(post_details)} unique posts' details extracted")
return post_details # Return list of dictionaries
def save_to_excel(post_details, filename):
"""Saves post details to Excel file."""
if not post_details:
print("No post details found to save")
return
print(f"Saving {len(post_details)} post details to {filename}...")
df = pd.DataFrame(post_details, columns=['Post URN', 'Post Link', 'Body Text']) # Columns for URN, link, and text
df.to_excel(filename, index=False)
print("File saved successfully.")
if __name__ == "__main__":
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10) # Implicit wait for elements
try:
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Handle security check
if "feed" not in driver.current_url and "login" in driver.current_url:
print("\nPlease complete security check in browser window")
input("Press Enter after logging in manually...")
post_details = scrape_post_details(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Changes Made
Modified the scrape_post_details function to extract the post link along with the URN and body text.
Updated the save_to_excel function to save the post details (URN, link, and text) to an Excel file.
Usage
Run the script to fetch the post details (URN, link, and text) and save them to an Excel file named "linkedin_post_details.xlsx".
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # Import for Keys.RETURN
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
# --- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_details.xlsx" # File to save post details
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of posts to collect details from
MAX_SCROLLS = 50 # Maximum number of scrolls
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN) # Submit the form
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def scrape_post_details(driver, url):
"""Scrolls dynamically and extracts post details (URN, body text, and link)."""
print(f"Navigating to company page: {url}")
driver.get(url)
time.sleep(10) # Wait for initial load
post_details = {} # Dictionary to store results: {urn: {'Post Link': link, 'Body Text': text}}
scroll_count = 0
consecutive_no_new = 0
max_consecutive = 5 # Stop if no new posts for this many scrolls
print(f"Starting collection (target: {TARGET_POSTS} posts)...")
while len(post_details) < TARGET_POSTS and scroll_count < MAX_SCROLLS:
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_details)
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference
if urn and urn not in post_details:
post_link = f"https://www.linkedin.com/feed/update/{urn}" # Construct post link
# Locate and extract the body text (adjust selector if needed)
text_element = post.find_element(By.CSS_SELECTOR, "div.update-components-text") # Example selector
body_text = text_element.text # Extract text
post_details[urn] = {'Post Link': post_link, 'Body Text': body_text} # Store with URN, link, and text
except NoSuchElementException:
print("Text element not found for a post. Skipping...")
except StaleElementReferenceException:
print("Stale element encountered; skipping.")
continue # Skip if element is stale
new_count = len(post_details)
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new posts. Total: {new_count}/{TARGET_POSTS}")
# Scroll down to load more
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
time.sleep(SCROLL_PAUSE_TIME) # Wait for content to load
if consecutive_no_new >= max_consecutive:
print(f"Stopping - No new posts for {max_consecutive} consecutive scrolls")
break
print(f"\nFinal count: {len(post_details)} unique posts' details extracted")
return [{'Post URN': urn, **details} for urn, details in post_details.items()] # Return list of dictionaries
def save_to_excel(post_details, filename):
"""Saves post details to Excel file."""
if not post_details:
print("No post details found to save")
return
print(f"Saving {len(post_details)} post details to {filename}...")
df = pd.DataFrame(post_details, columns=['Post URN', 'Post Link', 'Body Text']) # Columns for URN, link, and post
df.to_excel(filename, index=False)
print("File saved successfully.")
if __name__ == "__main__":
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10) # Implicit wait for elements
try:
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Handle security check
if "feed" not in driver.current_url and "login" in driver.current_url:
print("\nPlease complete security check in browser window")
input("Press Enter after logging in manually...")
post_details = scrape_post_details(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Changes Made
Modified the scrape_post_details function to store post details in a dictionary with the URN as the key, ensuring that only unique posts are stored.
Updated the function to return a list of dictionaries with the post details.
Usage
Run the script to fetch the post details (URN, link, and text) and save them to an Excel file named "linkedin_post_details.xlsx". The script will only fetch unique posts.
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # Import for Keys.RETURN
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
# --- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all&sortBy=RECENCY"
OUTPUT_FILE = "linkedin_post_details.xlsx" # File to save post details
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of posts to collect details from
MAX_SCROLLS = 50 # Maximum number of scrolls
def login_to_linkedin(driver, email, password):
"""Navigates to LinkedIn login page and signs in."""
print("Navigating to LinkedIn login page...")
driver.get("https://www.linkedin.com/login")
time.sleep(2)
try:
print("Entering credentials...")
email_field = driver.find_element(By.ID, "username")
email_field.send_keys(email)
password_field = driver.find_element(By.ID, "password")
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN) # Submit the form
print("Login successful.")
time.sleep(5)
except NoSuchElementException:
print("Could not find login fields. The page structure may have changed.")
driver.quit()
exit()
def scrape_post_details(driver, url):
"""Scrolls dynamically and extracts post details (URN, body text, link, and publication date)."""
print(f"Navigating to company page: {url}")
driver.get(url)
time.sleep(10) # Wait for initial load
post_details = {} # Dictionary to store results: {urn: {'Post Link': link, 'Body Text': text, 'Publication Date': date}}
scroll_count = 0
consecutive_no_new = 0
max_consecutive = 5 # Stop if no new posts for this many scrolls
print(f"Starting collection (target: {TARGET_POSTS} posts)...")
while len(post_details) < TARGET_POSTS and scroll_count < MAX_SCROLLS:
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_details)
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference
if urn and urn not in post_details:
post_link = f"https://www.linkedin.com/feed/update/{urn}" # Construct post link
# Locate and extract the body text (adjust selector if needed)
text_element = post.find_element(By.CSS_SELECTOR, "div.update-components-text") # Example selector
body_text = text_element.text # Extract text
# Locate and extract the publication date (adjust selector if needed)
try:
date_element = post.find_element(By.CSS_SELECTOR, "span.update-components-actor__sub-description > span")
publication_date = date_element.text # Extract date
except NoSuchElementException:
publication_date = "N/A" # Default if date not found
post_details[urn] = {'Post Link': post_link, 'Body Text': body_text, 'Publication Date': publication_date} # Store with URN, link, text, and date
except NoSuchElementException:
print("Text element not found for a post. Skipping...")
except StaleElementReferenceException:
print("Stale element encountered; skipping.")
continue # Skip if element is stale
new_count = len(post_details)
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new posts. Total: {new_count}/{TARGET_POSTS}")
# Scroll down to load more
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
time.sleep(SCROLL_PAUSE_TIME) # Wait for content to load
if consecutive_no_new >= max_consecutive:
print(f"Stopping - No new posts for {max_consecutive} consecutive scrolls")
break
print(f"\nFinal count: {len(post_details)} unique posts' details extracted")
return [{'Post URN': urn, **details} for urn, details in post_details.items()] # Return list of dictionaries
def save_to_excel(post_details, filename):
"""Saves post details to Excel file."""
if not post_details:
print("No post details found to save")
return
print(f"Saving {len(post_details)} post details to {filename}...")
df = pd.DataFrame(post_details, columns=['Post URN', 'Post Link', 'Body Text', 'Publication Date']) # Columns for URN, link, text, and date
df.to_excel(filename, index=False)
print("File saved successfully.")
if __name__ == "__main__":
linkedin_email = input("Enter your LinkedIn Email: ")
linkedin_password = getpass.getpass("Enter your LinkedIn Password: ")
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(10) # Implicit wait for elements
try:
login_to_linkedin(driver, linkedin_email, linkedin_password)
# Handle security check
if "feed" not in driver.current_url and "login" in driver.current_url:
print("\nPlease complete security check in browser window")
input("Press Enter after logging in manually...")
post_details = scrape_post_details(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Changes Made
Modified the scrape_post_details function to extract the publication date of the post.
Updated the save_to_excel function to save the post details (URN, link, text, and date) to an Excel file.
Usage
Run the script to fetch the post details (URN, link, text, and date) and save them to an Excel file named "linkedin_post_details.xlsx". The script will fetch the posts in the order of newest to oldest.