To modify your script to remove comments per day and the global comments part, while ensuring that the search function continues to run until you stop the script, you can follow the steps outlined below. The modified code is provided afterward:
-
Remove the comments_per_day and global_comments logic: This means we do not track how many comments have been made, and we simply keep searching based on a set of keywords without limiting the amount.
-
Run the search function indefinitely: You can use a loop that continues until you decide to exit, for example, using KeyboardInterrupt to stop the script.
Here's the modified version of your script:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
import yaml
import os
import logging
import pyperclip
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Suppress unnecessary log messages
os.environ['WDM_LOG_LEVEL'] = '0'
def normalize_cookie(cookie):
required_fields = ["name", "value", "domain", "path"]
normalized = {key: cookie.get(key, '') for key in required_fields}
if "expirationDate" in cookie:
normalized["expiry"] = int(cookie["expirationDate"])
normalized["secure"] = cookie.get("secure", True)
normalized["httpOnly"] = cookie.get("httpOnly", False)
same_site = cookie.get("sameSite", '').lower()
if same_site in ["no_restriction", "unspecified"]:
normalized["sameSite"] = "None"
elif same_site in ["strict", "lax", "none"]:
normalized["sameSite"] = same_site.capitalize()
else:
normalized["sameSite"] = "None"
return normalized
def load_settings():
logger.info("Loading settings from YAML file...")
script_dir = os.path.dirname(os.path.abspath(__file__))
settings_path = os.path.join(script_dir, 'settings.yaml')
if os.path.exists(settings_path):
with open(settings_path, 'r') as file:
settings_data = yaml.safe_load(file)
logger.info("Settings loaded successfully.")
return settings_data
else:
raise FileNotFoundError("Settings file not found. Please ensure settings.yaml exists.")
def wait_for_element(driver, locator, condition=EC.presence_of_element_located, timeout=20):
try:
element = WebDriverWait(driver, timeout).until(condition(locator))
return element
except TimeoutException:
logger.error(f"Timeout waiting for element: {locator}")
return None
def search_linkedin(driver, keyword, post_no_elements):
try:
logger.info(f"Searching for keyword: {keyword}")
search_url = f"https://www.linkedin.com/search/results/content/?datePosted=%22past-24h%22&keywords={keyword}&origin=FACETED_SEARCH&sid=&sortBy=%22date_posted%22"
driver.get(search_url)
if wait_for_element(driver, (By.CLASS_NAME, 'search-results-container')):
logger.info(f"Search completed for keyword: {keyword}")
script_dir = os.path.dirname(os.path.abspath(__file__))
urls_path = os.path.join(script_dir, 'urls.txt')
with open(urls_path, 'r') as file:
urls_in_file = [line.strip() for line in file.readlines()]
logger.info(f"Read {len(urls_in_file)} URLs from urls.txt file.")
time.sleep(3)
overflow_web_ios_small_xpath = f"(//button[contains(@class,'feed-shared-control-menu__trigger artdeco-button')])[ {post_no_elements} ]"
overflow_web_ios_small = wait_for_element(driver, (By.XPATH, overflow_web_ios_small_xpath))
if overflow_web_ios_small:
overflow_web_ios_small.click()
logger.info("Clicked post successfully.")
copy_link_xpath = "//*/text()[normalize-space(.)='Copy link to post']/parent::*"
copy_link_element = wait_for_element(driver, (By.XPATH, copy_link_xpath))
if copy_link_element:
copy_link_element.click()
logger.info("Clicked on 'Copy link to post' button successfully.")
time.sleep(3)
copied_url = pyperclip.paste()
logger.info(f"Copied URL: {copied_url}")
driver.execute_script("window.open('{}', '_blank');".format(copied_url))
with open(urls_path, 'a') as file:
file.write(f"{copied_url}\n\n")
logger.info("Copied URL added to urls.txt successfully.")
post_no_elements += 1
except TimeoutException:
logger.error(f"Timeout while searching for keyword: {keyword}")
def create_or_check_urls_file():
script_dir = os.path.dirname(os.path.abspath(__file__))
urls_path = os.path.join(script_dir, 'urls.txt')
if not os.path.exists(urls_path):
with open(urls_path, 'w') as file:
logger.info("urls.txt file created.")
else:
logger.info("urls.txt file already exists.")
def start_linkedin_automation(cookie, keywords, headless=True, close_browser_after=True):
logger.info("Starting LinkedIn automation...")
chrome_options = Options()
if headless:
chrome_options.add_argument("--headless")
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--incognito")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
try:
logger.info("Opening LinkedIn website...")
driver.get("https://www.linkedin.com")
if not wait_for_element(driver, (By.TAG_NAME, 'body'), EC.presence_of_element_located, timeout=30):
logger.error("Failed to load LinkedIn home page.")
return
logger.info("Loading cookies...")
try:
for c in cookie['cookies']:
normalized_cookie = normalize_cookie(c)
driver.add_cookie(normalized_cookie)
except KeyError as e:
logger.error(f"Error loading cookies, missing key: {str(e)}")
return
except Exception as e:
logger.error(f"Unexpected error while loading cookies: {str(e)}")
return
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.refresh()
logger.info("Cookies loaded and page refreshed.")
if "feed" not in driver.current_url:
logger.error("Login failed. Please check the cookie.")
return
logger.info("Logged in successfully!")
create_or_check_urls_file()
# Continuously search until manually interrupted
post_no_elements = 1
while True: # Infinite loop
for keyword in keywords:
search_linkedin(driver, keyword, post_no_elements)
post_no_elements += 1 # Increase post_no_elements to make subsequent searches dynamic
except KeyboardInterrupt:
logger.info("Script interrupted by user.")
finally:
if close_browser_after:
logger.info("Closing browser...")
try:
driver.quit()
logger.info("Browser closed after completing the comments.")
except Exception as e:
logger.error(f"Error occurred while closing the browser: {str(e)}")
else:
logger.info("Automation complete. Browser will remain open for manual inspection.")
Key Modifications:
-
Removed comments_per_day and global_comments: The logic to limit the number of comments made has been eliminated. The new approach allows the script to run indefinitely.
-
Continuous Loop: A while True: loop has been implemented which allows the searches to continue for the provided keywords. You can stop the script using CTRL+C in the terminal/command prompt where the script is running.
-
KeyboardInterrupt Handling: The script now catches KeyboardInterrupt to offer a graceful exit when you decide to stop it.
This modified script will keep searching for the provided keywords on LinkedIn until manually stopped. Make sure you observe LinkedIn's usage policy and avoid automation that might violate their terms.