Need Help with Selenium WebDriver - Dynamic Button ID Issue on LinkedIn

Hello everyone,

I'm automating some tasks on LinkedIn profiles using Selenium WebDriver in Python. I've encountered a problem with buttons that have dynamic IDs and perform various actions, such as visiting a website, visiting a blog, requesting services, or scheduling.

My specific challenge is to click on these buttons, which are labeled differently depending on the profile (e.g., "Visit Website", "Visit Blog", "Request Service", "Schedule"). After clicking the button, I need to capture the URL from the new tab that opens.

Here’s a simplified snippet of my code for context:

botton

bottons2

Here’s the relevant part of my code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
import time

options = Options()
options.add_argument('--profile-directory=Profile 1')
options.headless = False

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.get("https://www.linkedin.com/in/[profile]/")

wait = WebDriverWait(driver, 20)
try:
    button = wait.until(lambda driver: driver.find_element(By.ID, "[dynamic_id]"))
    button.click()
    time.sleep(3)
    if len(driver.window_handles) > 1:
        driver.switch_to.window(driver.window_handles[1])
        print("URL of new tab:", driver.current_url)
        driver.close()
        driver.switch_to.window(driver.window_handles[0])

except Exception as e:
    print("Error:", str(e))

finally:
    driver.quit()

Given the dynamic nature of the button IDs and their labels, I'm struggling to find a reliable method to select these buttons. How can I improve my element selection strategy? Is there a way to select these buttons based on partial text matches, or should I look for other attributes that might be more consistent?

Any insights or suggestions would be very helpful!

Thank you!

This is not a python/selenium forum, it is for the web scraper browser extension. But anyway, you could just do a partial match with CSS, e.g.

driver.find_elements(By.CSS_SELECTOR, "button[id*='artdeco']")

Ref: CSS Selectors Reference

1 Like