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
Below is the updated version of your code. I've extended it to include a new function that fetches the body text of each post from the collected links. Here's a high-level overview of the changes:
Key Additions:
New Function: fetch_post_texts:
This function takes the list of post URLs and the Selenium driver as inputs.
For each URL, it navigates to the post page.
It locates the body text of the post (using a CSS selector based on common LinkedIn page structures) and extracts it.
It handles potential errors, such as pages not loading or elements not being found.
The results are stored in a list of dictionaries, which is then converted to a Pandas DataFrame.
Integration into the Main Script:
After scraping and saving the links (in the scrape_post_links and save_to_excel functions), I've added a call to the new fetch_post_texts function.
The extracted data is saved to a new Excel file, e.g., "linkedin_post_details.xlsx", with columns for 'Post URL' and 'Body Text'.
This ensures the driver remains open during the fetching process and only quits afterward.
Important Notes:
CSS Selector for Body Text: I've used By.CSS_SELECTOR, "div.update-components-text" as an example selector for the post body. This is based on common LinkedIn post structures, but LinkedIn's HTML can change. You may need to inspect the actual page (right-click on a post and select "Inspect" in your browser) and adjust the selector if it doesn't work. For instance, it could be something like div.lt-line-clamp or div.feed-shared-update-v2__description.
Error Handling: The code includes checks for common issues like NoSuchElementException (if the text element isn't found) or other exceptions (e.g., page load failures). If an error occurs for a specific post, it will mark the body text as 'N/A' or 'Error' and continue.
Performance Considerations: Fetching text for each post involves navigating to individual pages, which can be slow (especially with 200+ links). I've added waits to handle loading times, but if you have many links, this might take several minutes. You could optimize by using explicit waits instead of time.sleep.
Rate Limiting: LinkedIn may block or rate-limit your requests if you hit too many pages quickly. I've kept the pauses conservative, but monitor for any blocks.
: Ensure you have , , and installed (via ).
User
I don't want to fetch the links but just the body texts
Assistant
It seems like you want to modify the script to directly extract the body texts of the posts from the LinkedIn company page without first collecting and saving the post links. This is a reasonable optimization, as we can combine the scrolling process with text extraction.
To achieve this, I'll update the code as follows:
Skip the link collection step entirely.
In a new function, scroll through the company page and directly extract the body text from each visible post.
Handle potential issues like truncated text (e.g., LinkedIn might show only a preview; if needed, we could add logic to click "See more," but I'll keep it simple for now).
Save the extracted body texts directly to an Excel file.
Key Changes:
New Function: scrape_post_texts:
This will replace the old scrape_post_links function.
It scrolls the page and, for each post, extracts the body text using a CSS selector (e.g., based on the post's text element).
I'll use a selector like By.CSS_SELECTOR, "div.update-components-text" for the body text, but you may need to adjust it based on LinkedIn's actual page structure (inspect the page in your browser).
Output: The script will save a DataFrame with the body texts to a new Excel file, e.g., "linkedin_post_texts.xlsx". Each row will include the body text (and optionally the post's URN for reference).
Stopping Conditions: We'll still use limits like a target number of posts and maximum scrolls to prevent infinite loops.
Error Handling: If a post's text isn't found, we'll mark it as 'N/A' and continue.
Important Notes:
Text Extraction: On the company feed, posts might be truncated. If you need the full text, the script might require additional steps (e.g., clicking into each post). For now, this version extracts the visible text.
CSS Selector: LinkedIn's HTML can change, so verify the selector by inspecting a post on the page. If it doesn't work, common alternatives might include div.lt-line-clamp or div.feed-shared-update-v2__description.
Performance: Extracting text while scrolling should be faster than visiting each link, but it still involves dynamic loading.
Dependencies: Ensure you have selenium, pandas, and webdriver-manager installed.
Here's the updated 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
It looks like you're encountering an error because your script is trying to read a file called linkedin_post_links.xlsx, but that file doesn't exist in your current directory. This error is likely due to a mismatch between the code you're running and the latest version I provided.
Understanding the Error:
The traceback shows that on line 74 of your linkedin_scraper.py file, there's a line: post_links_df = pd.read_excel("linkedin_post_links.xlsx").
This line attempts to load an Excel file that hasn't been created yet (or doesn't exist for some reason).
However, in the most recent code I shared (the one for directly scraping post texts), there is no such line. This suggests you're running an older version of the script from earlier in our conversation, or you've made some custom modifications.
In the initial versions of the code, we were scraping and saving post links to that file, but in the latest version (which focuses on directly extracting body texts), we don't need to read from or write to linkedin_post_links.xlsx at all. Instead, the script saves directly to linkedin_post_texts.xlsx.
How to Fix This:
Update Your Code: Replace your entire linkedin_scraper.py file with the latest code I provided in my previous response. This version doesn't include the problematic line and is designed to scrape post texts directly without dealing with link files.
Here's the latest code again for convenience. Copy and paste it into your linkedin_scraper.py file:
python
User
give me a fixed code
Assistant
It seems like you're still running into issues with your script, possibly due to remnants of older code or configuration problems. Based on our conversation, the "fixed code" should be the latest version that directly scrapes and saves the body texts of the posts without trying to read any external files like "linkedin_post_links.xlsx".
Here's the complete, updated code. This version:
Directly navigates to the LinkedIn company page after login.
Scrolls through the page and extracts the body texts of the posts.
Saves the results to "linkedin_post_texts.xlsx".
Includes all necessary imports and error handling.
Make sure to:
Replace your entire linkedin_scraper.py file with this code.
Install any missing dependencies by running pip install selenium pandas webdriver-manager in your terminal (from your virtual environment if you're using one).
Run the script from the correct directory.
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
Below is the updated version of your code. I've modified it to fetch both the body text of each post and the full link to that post. Here's a quick summary of the changes:
Key Changes:
In scrape_post_texts function:
When processing each post, after extracting the URN, I construct the full post link. The URN is typically in the format urn:li:activity:123456789, so I extract the ID (e.g., 123456789) and form the URL as https://www.linkedin.com/feed/update/{ID}.
The post_texts list now includes an additional key: 'Post Link', so each dictionary will look like: {'Post URN': urn, 'Post Link': full_link, 'Body Text': body_text}.
In save_to_excel function:
The DataFrame now includes the new column for the post link, so it saves with columns: ['Post URN', 'Post Link', 'Body Text'].
This ensures that for each post, you get:
The URN (for reference).
The full link (e.g., https://www.linkedin.com/feed/update/123456789).
The body text.
Updated Code:
Here's the complete, fixed code with these modifications:
python
User
edit the code so that only unique posts are fetched
Assistant
Below is the updated version of your code, modified to ensure that only unique posts are fetched. I've implemented this by using a set to track unique Post URNs. Before adding a post to the list, the code checks if the URN has already been seen. If it has, the post is skipped.
Key Changes:
In scrape_post_texts function:
Added a set called seen_urns to keep track of unique URNs.
Inside the loop for processing posts, before extracting the link and text, check if the URN is in seen_urns. If it is, skip the post. If not, process it and add the URN to the set.
This ensures that only unique posts (based on URN) are added to the post_details list.
Updated the print statements to reflect the addition of unique posts only.
Why URN?: The URN is a unique identifier for each LinkedIn post, so it's the best way to check for duplicates.
Impact on Logic:
The while loop still targets TARGET_POSTS unique posts.
The script will continue scrolling until it reaches the target number of unique posts or hits the maximum scrolls.
This change prevents duplicates from being added to the output list and the final Excel file.
Updated Code:
python
User
could you update the code so that the posts are fetched in the file from newest to the oldest?
Assistant
Below is the updated version of your code, modified to ensure that the posts are fetched and saved in order from newest to oldest. Since LinkedIn's feed naturally loads posts in reverse chronological order (newest first), the code will collect them in this order. However, to explicitly sort the final output, I've added the following enhancements:
Key Changes:
Extract Post Timestamp: For each post, the code now extracts the timestamp using a common LinkedIn selector (e.g., time element). This allows us to sort the posts based on the actual date/time.
Sort Before Saving: After collecting all posts, the list is sorted by the 'Post Timestamp' in descending order (newest first) before saving to the Excel file.
Handle Timestamp Extraction: If the timestamp element is not found for a post, it's marked as 'N/A', and the post is still included but might not sort correctly for that entry.
Updated Dictionary Structure: Each post dictionary now includes a new key: 'Post Timestamp', so the output will have columns: ['Post URN', 'Post Link', 'Body Text', 'Post Timestamp'].
Sorting Logic: In the save_to_excel function, the DataFrame is sorted by 'Post Timestamp' in descending order before writing to the file. This ensures the final Excel file has posts ordered from newest to oldest.
Important Notes:
Timestamp Selector: I'm using By.CSS_SELECTOR, "time" as the selector for the timestamp element, which is common on LinkedIn posts. If this doesn't work, inspect a LinkedIn post (right-click > Inspect) and adjust it (e.g., to "time.relative-time" or similar).
Error Handling: If a timestamp isn't found, it's set to 'N/A', and the post is still added to the list.
Uniqueness: The code still ensures only unique posts are fetched, as per your previous request.
Output File: The posts will be saved in sorted order in linkedin_post_details.xlsx.
Here's the complete updated code:
python
User
add the date of publication, update the code
Assistant
Below is the updated version of your code with the addition of the "date of publication" as a separate field. Here's a quick summary of the changes:
Key Changes:
Extract and Add Publication Date: For each post, the code now extracts the full timestamp (as before) and derives a new field called "Publication Date" from it. This field contains only the date portion (e.g., '2023-10-01') in 'YYYY-MM-DD' format.
Handling in Dictionary: Each post dictionary now includes an additional key: 'Publication Date'. So, the structure is: {'Post URN': urn, 'Post Link': full_link, 'Body Text': body_text, 'Post Timestamp': full_timestamp, 'Publication Date': publication_date}.
In scrape_post_texts Function: After extracting the full timestamp, I use the datetime module to parse it and extract just the date. If the timestamp is not found or invalid, 'Publication Date' is set to 'N/A'.
In save_to_excel Function: The DataFrame now includes the new column, and the file is still sorted by 'Post Timestamp' in descending order (newest first).
Imports: Added import datetime to handle date parsing.
This ensures that:
"Post Timestamp" retains the full ISO datetime string (e.g., '2023-10-01T12:00:00Z').
"Publication Date" is a simplified date string (e.g., '2023-10-01').
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, TimeoutException
# --- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_links.xlsx"
DETAILS_OUTPUT_FILE = "linkedin_post_details.xlsx" # New file for post details
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_LINKS = 200 # Minimum number of links to collect
MAX_SCROLLS = 50 # Maximum number of scrolls
FETCH_PAUSE_TIME = 5 # Time to wait after loading a post page
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 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
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:
current_posts = driver.find_elements(By.CSS_SELECTOR, "div[data-urn*='urn:li:activity:']")
previous_count = len(post_links)
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}")
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}")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
scroll_count += 1
print(f"Scroll #{scroll_count} completed")
time.sleep(SCROLL_PAUSE_TIME)
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
print(f"Saving {len(links)} links to {filename}...")
df = pd.DataFrame(links, columns=['Post URL'])
df.to_excel(filename, index=False)
print("File saved successfully.")
def fetch_post_texts(driver, links):
"""Fetches the body text for each post URL."""
post_details = [] # List to store results: [{'URL': link, 'Body Text': text}]
print(f"Starting to fetch body text for {len(links)} posts...")
for link in links:
try:
driver.get(link)
time.sleep(FETCH_PAUSE_TIME) # Wait for the page to fully load
try:
# Locate the body text element (adjust selector if needed)
post_text_element = driver.find_element(By.CSS_SELECTOR, "div.update-components-text")
body_text = post_text_element.text # Extract the text
post_details.append({'Post URL': link, 'Body Text': body_text})
print(f"Successfully fetched text for {link}")
except NoSuchElementException:
print(f"No text element found for {link}")
post_details.append({'Post URL': link, 'Body Text': 'N/A'}) # Mark as not available
except TimeoutException:
print(f"Timeout while loading {link}")
post_details.append({'Post URL': link, 'Body Text': 'Timeout Error'})
except Exception as e:
print(f"Error fetching {link}: {e}")
post_details.append({'Post URL': link, 'Body Text': 'Error'})
print(f"Finished fetching texts for {len(post_details)} posts.")
return post_details
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...")
all_links = scrape_post_links(driver, COMPANY_URL)
save_to_excel(all_links, OUTPUT_FILE)
# New: Fetch and save post details
if all_links:
post_details = fetch_post_texts(driver, all_links)
df_details = pd.DataFrame(post_details)
df_details.to_excel(DETAILS_OUTPUT_FILE, index=False)
print(f"Post details saved successfully to {DETAILS_OUTPUT_FILE}")
else:
print("No links available to fetch post texts.")
finally:
print("Closing browser")
driver.quit()
How to Run This:
Save the code to a file (e.g., linkedin_scraper.py).
Run it using Python: python linkedin_scraper.py.
Enter your LinkedIn credentials when prompted.
The script will:
Log in.
Scrape and save the post links to linkedin_post_links.xlsx.
Fetch the body text for each link and save it to linkedin_post_details.xlsx.
Check the output files in your current directory.
Potential Improvements:
Explicit Waits: Replace time.sleep with WebDriverWait for more reliable waiting (e.g., wait for the post text element to be visible).
Proxy or Headless Mode: If you're dealing with rate limits, consider running Chrome in headless mode or using a proxy.
Testing: Test with a small number of links first to verify the selector and error handling.
Data Cleaning: The extracted text might include extra whitespace or HTML artifacts; you could add cleaning steps using string methods.
If you encounter issues (e.g., the CSS selector doesn't work), share more details about the page structure, and I can help refine it!
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
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)
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) # Assuming Keys is imported; add if needed
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
post_texts = [] # List to store results: [{'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.")
# 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
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: ")
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()
How This Works:
Login: The script logs you into LinkedIn as before.
Navigation and Scraping: It goes to the company page and scrolls while extracting the body text from each post.
For each post element, it tries to find the text using the specified CSS selector.
It stores the text along with the post's URN (for easy reference) in a list of dictionaries.
Saving: After scrolling stops (either by reaching the target or hitting the max scrolls), it saves the data to an Excel file with columns: Post URN and Body Text.
Output File: You'll get a file named linkedin_post_texts.xlsx containing the extracted texts.
Potential Improvements or Adjustments:
If Text is Truncated: If the extracted text is incomplete, you might need to add code to click a "See more" button. For example, locate an element like button[data-control-name="see_more"] and click it before extracting text. Let me know if you want this added.
Testing the Selector: Open the company page in your browser, right-click on a post's text, select "Inspect," and find the correct CSS selector. Update the line text_element = post.find_element(By.CSS_SELECTOR, "div.update-components-text") accordingly.
Error Handling: The code skips posts where the text element isn't found, but you can expand this if needed.
Running the Script: Save this code to a file (e.g., linkedin_scraper.py), install the required libraries if you haven't (pip install selenium pandas webdriver-manager), and run it with python linkedin_scraper.py.
If this doesn't work as expected (e.g., due to page changes), provide more details about the errors or the page structure, and I can refine it further!
import time
import getpass
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
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)
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
post_texts = [] # List to store results: [{'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.")
# Skip or 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
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: ")
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()
Manually Remove the Problematic Line:
If you don't want to replace the entire file, open linkedin_scraper.py in a text editor.
Go to line 74 (or search for post_links_df = pd.read_excel("linkedin_post_links.xlsx")).
Delete or comment out that line (e.g., add a # at the beginning to make it # post_links_df = pd.read_excel("linkedin_post_links.xlsx")).
Save the file and try running it again.
Run the Script Again:
Make sure you have all the required libraries installed: Run pip install selenium pandas webdriver-manager in your terminal (from your virtual environment if you're using one).
Navigate to your script's directory in the terminal: cd /Users/arturwillonski/Documents/scrapper
Activate your virtual environment if needed (e.g., source venv/bin/activate on macOS).
Run the script: /Users/arturwillonski/Documents/scrapper/venv/bin/python linkedin_scraper.py
Additional Tips:
Why This Happened: This error often occurs when code evolves through iterations (like in our conversation), and an old snippet remains in your file.
Test Incrementally: After updating, run the script and watch for any new errors. If you get issues related to the CSS selector (e.g., "Text element not found"), you may need to inspect the LinkedIn page and adjust the selector in the scrape_post_texts function.
Common Pitfalls:
Ensure you're logged into LinkedIn and that the page loads correctly.
If you encounter permission issues or blocks from LinkedIn, you might need to handle captchas or slow down the script further.
If you run into any other errors after this fix, please share the full traceback or more details about what's happening, and I'll help you troubleshoot!
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)
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
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
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: ")
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()
How to Use This Fixed Code:
Save the File: Copy the above code into your linkedin_scraper.py file in /Users/arturwillonski/Documents/scrapper/.
Run It:
Open your terminal.
Navigate to the directory: cd /Users/arturwillonski/Documents/scrapper
Activate your virtual environment if needed: source venv/bin/activate
Run the script: ./venv/bin/python linkedin_scraper.py
Common Troubleshooting:
CSS Selector Issue: If you get errors like "Text element not found," LinkedIn's page structure might have changed. Inspect a post on the LinkedIn page (right-click > Inspect) and update the selector in scrape_post_texts (e.g., change "div.update-components-text" to something like "div.lt-line-clamp").
Permissions or Blocks: If LinkedIn blocks you, try adding more delays or running the script less frequently.
Dependencies: Double-check that you have Chrome installed and that webdriver-manager can download the ChromeDriver.
If you encounter any new errors, please share the full traceback, and I'll help you fix it!
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" # Updated file name for clarity
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)
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 and links from posts."""
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, e.g., 'urn:li:activity:123456789'
if urn and urn.startswith('urn:li:activity:'):
# Extract the ID from the URN
post_id = urn.split(':')[-1] # Get the last part, e.g., '123456789'
full_link = f"https://www.linkedin.com/feed/update/{post_id}" # Construct full 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
# Append to the list with URN, link, and text
post_details.append({
'Post URN': urn,
'Post Link': full_link,
'Body Text': body_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_texts(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
How This Works:
Fetching the Link: In the loop inside scrape_post_texts, I parse the URN to extract the post ID and construct the full link. This link is then stored in the dictionary for each post.
Output File: The script will now save to linkedin_post_details.xlsx (I updated the filename for clarity, but you can change it back if needed). The Excel file will have three columns:
Post URN: The full URN (e.g., urn:li:activity:123456789).
Post Link: The clickable URL (e.g., https://www.linkedin.com/feed/update/123456789).
Body Text: The text content of the post.
Notes:
CSS Selector: The selector "div.update-components-text" is still used for the body text. If this doesn't work on your LinkedIn page, inspect a post (right-click > Inspect in your browser) and update it in the code.
Error Handling: If a post's text or URN isn't found, it's skipped. You can enhance this by uncommenting the optional line to add entries with 'N/A' values.
Running the Code:
Replace your existing script file with this one.
Install dependencies if needed: pip install selenium pandas webdriver-manager.
Run it from your terminal as before.
If you run into any issues (e.g., errors about elements not found or LinkedIn blocking the script), let me know the details, and I'll help refine it further!
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 body texts
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of unique posts to collect
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_texts(driver, url):
"""Scrolls dynamically and extracts body texts and links from unique posts only."""
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}]
seen_urns = set() # Set to track unique URNs
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} unique 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) # Track unique posts added
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference, e.g., 'urn:li:activity:123456789'
if urn and urn.startswith('urn:li:activity:') and urn not in seen_urns:
# Extract the ID from the URN
post_id = urn.split(':')[-1] # Get the last part, e.g., '123456789'
full_link = f"https://www.linkedin.com/feed/update/{post_id}" # Construct full 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
# Add to the list
post_details.append({
'Post URN': urn,
'Post Link': full_link,
'Body Text': body_text
})
seen_urns.add(urn) # Add URN to the set
elif urn in seen_urns:
# Skip if URN is already seen
continue
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) # Now based on unique posts
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new unique posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new unique posts. Total unique: {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 unique 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 with only unique posts
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)} unique 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_texts(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Explanation of Changes:
Uniqueness Check: The line if urn and urn.startswith('urn:li:activity:') and urn not in seen_urns: ensures that only unseen URNs are processed. After adding a post, the URN is added to seen_urns.
Print Statements: Updated to say "No new unique posts" and "Added X new unique posts" to reflect that we're only counting unique additions.
Edge Cases: If a post's URN is missing or invalid, it's skipped. This maintains the integrity of the data.
Output: The final Excel file (linkedin_post_details.xlsx) will only contain unique posts, with columns for Post URN, Post Link, and Body Text.
How to Use:
Replace your existing script file with this updated code.
Run it as before: Activate your virtual environment and execute the script.
If you encounter issues (e.g., due to LinkedIn's changing page structure), check the CSS selector for the body text and adjust it if needed.
This should resolve your request. If you have any further modifications or run into errors, let me know!
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 body texts
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of unique posts to collect
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_texts(driver, url):
"""Scrolls dynamically and extracts body texts, links, and timestamps from unique posts only."""
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, 'Post Timestamp': timestamp}]
seen_urns = set() # Set to track unique URNs
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} unique 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) # Track unique posts added
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference, e.g., 'urn:li:activity:123456789'
if urn and urn.startswith('urn:li:activity:') and urn not in seen_urns:
# Extract the ID from the URN
post_id = urn.split(':')[-1] # Get the last part, e.g., '123456789'
full_link = f"https://www.linkedin.com/feed/update/{post_id}" # Construct full 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 timestamp
try:
timestamp_element = post.find_element(By.CSS_SELECTOR, "time") # Selector for timestamp
timestamp = timestamp_element.get_attribute('datetime') # Get ISO datetime, e.g., '2023-10-01T12:00:00Z'
except NoSuchElementException:
timestamp = 'N/A' # Fallback if timestamp not found
# Add to the list
post_details.append({
'Post URN': urn,
'Post Link': full_link,
'Body Text': body_text,
'Post Timestamp': timestamp # Add timestamp
})
seen_urns.add(urn) # Add URN to the set
elif urn in seen_urns:
# Skip if URN is already seen
continue
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) # Now based on unique posts
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new unique posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new unique posts. Total unique: {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 unique 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 with only unique posts
def save_to_excel(post_details, filename):
"""Saves post details to Excel file, sorted by Post Timestamp (newest first)."""
if not post_details:
print("No post details found to save")
return
print(f"Saving {len(post_details)} unique post details to {filename}...")
# Convert to DataFrame and sort by 'Post Timestamp' descending (newest first)
df = pd.DataFrame(post_details, columns=['Post URN', 'Post Link', 'Body Text', 'Post Timestamp'])
# Sort by 'Post Timestamp'. Handle 'N/A' by treating it as oldest
df['Post Timestamp'] = pd.to_datetime(df['Post Timestamp'], errors='coerce') # Convert to datetime, NaT for 'N/A'
df = df.sort_values(by='Post Timestamp', ascending=False) # Descending: newest first
df.to_excel(filename, index=False)
print("File saved successfully, sorted from newest to oldest.")
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_texts(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Explanation of Changes:
Timestamp Extraction: In scrape_post_texts, I added code to find the time element and extract its datetime attribute. This is stored in the dictionary for each post.
Sorting in save_to_excel:
The DataFrame is created with the new column.
pd.to_datetime converts the timestamp to a datetime object, handling any invalid values (like 'N/A') as NaT (Not a Time).
sort_values(by='Post Timestamp', ascending=False) sorts the DataFrame so that the most recent timestamps come first.
Output: The Excel file will now have posts ordered from newest to oldest based on the timestamp. If a timestamp is missing (e.g., 'N/A'), those rows will be placed at the end.
How to Use:
Replace your existing script file with this updated code.
Run it as before: Ensure your virtual environment is activated and execute the script.
If you encounter issues (e.g., "NoSuchElementException" for the timestamp), verify the selector by inspecting a LinkedIn post and update it in the code.
This should achieve your goal. If you need further adjustments, let me know!
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
import datetime # For parsing and formatting dates
# --- Configuration ---
COMPANY_URL = "https://www.linkedin.com/company/euipo/posts/?feedView=all"
OUTPUT_FILE = "linkedin_post_details.xlsx" # File to save body texts
SCROLL_PAUSE_TIME = 10 # Time to wait after scrolling
TARGET_POSTS = 200 # Minimum number of unique posts to collect
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_texts(driver, url):
"""Scrolls dynamically and extracts body texts, links, timestamps, and publication dates from unique posts only."""
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, 'Post Timestamp': timestamp, 'Publication Date': date}]
seen_urns = set() # Set to track unique URNs
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} unique 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) # Track unique posts added
for post in current_posts:
try:
urn = post.get_attribute("data-urn") # Get URN for reference, e.g., 'urn:li:activity:123456789'
if urn and urn.startswith('urn:li:activity:') and urn not in seen_urns:
# Extract the ID from the URN
post_id = urn.split(':')[-1] # Get the last part, e.g., '123456789'
full_link = f"https://www.linkedin.com/feed/update/{post_id}" # Construct full 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 timestamp
try:
timestamp_element = post.find_element(By.CSS_SELECTOR, "time") # Selector for timestamp
full_timestamp = timestamp_element.get_attribute('datetime') # Get ISO datetime, e.g., '2023-10-01T12:00:00Z'
# Derive publication date from full timestamp
if full_timestamp:
pub_date = datetime.datetime.fromisoformat(full_timestamp[:-1]) # Remove 'Z' and parse
publication_date = pub_date.date().strftime('%Y-%m-%d') # Format as 'YYYY-MM-DD'
else:
publication_date = 'N/A'
except NoSuchElementException:
full_timestamp = 'N/A'
publication_date = 'N/A'
# Add to the list
post_details.append({
'Post URN': urn,
'Post Link': full_link,
'Body Text': body_text,
'Post Timestamp': full_timestamp, # Full timestamp
'Publication Date': publication_date # Just the date
})
seen_urns.add(urn) # Add URN to the set
elif urn in seen_urns:
# Skip if URN is already seen
continue
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) # Now based on unique posts
if new_count == previous_count:
consecutive_no_new += 1
print(f"No new unique posts in scroll #{scroll_count}. Consecutive: {consecutive_no_new}")
else:
consecutive_no_new = 0
print(f"Added {new_count - previous_count} new unique posts. Total unique: {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 unique 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 with only unique posts
def save_to_excel(post_details, filename):
"""Saves post details to Excel file, sorted by Post Timestamp (newest first)."""
if not post_details:
print("No post details found to save")
return
print(f"Saving {len(post_details)} unique post details to {filename}...")
# Convert to DataFrame and sort by 'Post Timestamp' descending (newest first)
df = pd.DataFrame(post_details, columns=['Post URN', 'Post Link', 'Body Text', 'Post Timestamp', 'Publication Date'])
# Sort by 'Post Timestamp'. Handle 'N/A' by treating it as oldest
df['Post Timestamp'] = pd.to_datetime(df['Post Timestamp'], errors='coerce') # Convert to datetime, NaT for 'N/A'
df = df.sort_values(by='Post Timestamp', ascending=False) # Descending: newest first
df.to_excel(filename, index=False)
print("File saved successfully, sorted from newest to oldest.")
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_texts(driver, COMPANY_URL)
save_to_excel(post_details, OUTPUT_FILE)
finally:
print("Closing browser")
driver.quit()
Explanation of Changes:
Publication Date Derivation: In scrape_post_texts, after getting the full timestamp, I parse it using datetime.datetime.fromisoformat and format it as just the date (e.g., '2023-10-01').
Dictionary Update: Each post now has both 'Post Timestamp' (full string) and 'Publication Date' (date only).
DataFrame and Sorting: The DataFrame in save_to_excel includes the new column, and sorting is still based on 'Post Timestamp'.
Error Handling: If the timestamp is missing, both 'Post Timestamp' and 'Publication Date' are set to 'N/A', ensuring the code doesn't break.
How to Use:
Replace your existing script file with this updated code.
Run it as before: Activate your virtual environment and execute the script.
Output File: The Excel file (linkedin_post_details.xlsx) will now have columns: ['Post URN', 'Post Link', 'Body Text', 'Post Timestamp', 'Publication Date'], sorted from newest to oldest.
If you encounter any issues (e.g., with timestamp parsing or selectors), provide more details, and I'll refine it further!