You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium Python自动化LinkedIn时,连接按钮脚本失效求助

LinkedIn批量点击Connect按钮失效的解决方案

我用Selenium实现LinkedIn自动化,目标是搜索娱乐记者并批量点击Connect按钮建立连接。登录和搜索功能正常,但注释//************ from here script is not working ****************************之后的代码无法运行,没法完成点击所有Connect按钮的操作。

原代码如下:

from selenium import webdriver
import time

driver = webdriver.Chrome('C:\Users\SUJASH\AppData\Local\Temp\HZ$D.705.3782\HZ$D.705.3783\chromedriver.exe')
driver.get('https://www.linkedin.com')
time.sleep(2)

#********** LOG IN *************

username = driver.find_element("id", "session_key")
password = driver.find_element("id", "session_password")
username.send_keys('HIDDEN_ON_SOF')
password.send_keys('HIDDEN_ON_SOF')
time.sleep(2)

submit = driver.find_element("xpath", "//button[@type='submit']").click()

#*********** SEARCH ***********
driver.get('https://www.linkedin.com/search/results/people/?heroEntityKey=urn%3Ali%3Aautocomplete%3A1975299068&keywords=entertainment%20journalist&origin=CLUSTER_EXPANSION&sid=uv!')
time.sleep(5)

#************ from here script is not working ****************************

all_buttons = driver.find_elements("tag_name", "button")
connect_buttons = [btn for btn in all_buttons if btn.text == "Connect"]

for btn in connect_buttons:
    driver.execute_script("arguments[0].click();", btn)
    time.sleep(2)
    send = driver.find_element("xpath" , "//button[@aria-label='Send now']")
    driver.execute_script("arguments[0].click();", send)
    close = driver.find_element("xpath" , "//button[@aria-label='Dismiss']")
    driver.execute_script("arguments[0].click();", close)
    time.sleep(2)

问题根源

  1. 按钮定位逻辑缺陷:通过tag_name获取所有按钮再筛选文本的方式极不可靠——LinkedIn的按钮文本可能因加载延迟、页面语言切换或元素处于不可见区域导致匹配失败;同时页面中存在大量无关按钮,会混入筛选结果。
  2. 等待机制不合理:固定time.sleep()无法适配页面加载速度,元素未渲染完成就执行操作会直接报错;弹窗元素(Send now、Dismiss)也需要等待其完全可点击后再操作。
  3. 无异常兼容处理:部分用户可能需要填写邀请备注,或者当前账号无法向该用户发送邀请,直接定位Send now按钮会因元素不存在导致脚本中断。

修正后的代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 初始化浏览器(建议将chromedriver路径配置到环境变量,避免硬编码绝对路径)
driver = webdriver.Chrome('C:\Users\SUJASH\AppData\Local\Temp\HZ$D.705.3782\HZ$D.705.3783\chromedriver.exe')
driver.maximize_window()
driver.get('https://www.linkedin.com')
time.sleep(2)

# 登录流程
username = driver.find_element(By.ID, "session_key")
password = driver.find_element(By.ID, "session_password")
username.send_keys('HIDDEN_ON_SOF')
password.send_keys('HIDDEN_ON_SOF')
time.sleep(2)
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(3)

# 跳转搜索结果页
driver.get('https://www.linkedin.com/search/results/people/?heroEntityKey=urn%3Ali%3Aautocomplete%3A1975299068&keywords=entertainment%20journalist&origin=CLUSTER_EXPANSION&sid=uv!')
# 等待搜索结果容器加载完成
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "search-results-container")))

# 批量处理Connect按钮
try:
    # 精准定位所有Connect按钮:通过aria-label包含"Connect with"的特征
    connect_buttons = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, "//button[contains(@aria-label, 'Connect with')]"))
    )
    
    for index, btn in enumerate(connect_buttons):
        # 滚动到按钮可见位置,避免因元素在视口外导致点击失败
        driver.execute_script("arguments[0].scrollIntoView(true);", btn)
        time.sleep(1)
        btn.click()
        time.sleep(1)
        
        # 处理邀请弹窗:兼容直接发送和需要备注两种情况
        try:
            # 尝试点击"Send now"按钮
            send_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Send now']"))
            )
            send_btn.click()
        except:
            # 如果遇到需要填写备注的弹窗,直接关闭
            close_btn = WebDriverWait(driver, 5).until(
                EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Dismiss']"))
            )
            close_btn.click()
        time.sleep(2)
        
except Exception as e:
    print(f"操作过程中出现错误: {str(e)}")
finally:
    # 可选:完成操作后关闭浏览器
    # driver.quit()
    pass

关键优化点

  • 精准元素定位:利用aria-label的特征匹配Connect按钮,彻底避免无关按钮干扰;
  • 显式等待替代固定休眠:使用WebDriverWait等待元素加载完成,大幅提升脚本稳定性;
  • 滚动至可见区域:确保按钮处于浏览器视口内再点击,解决元素不可见导致的点击失败问题;
  • 异常兼容处理:针对不同弹窗场景做容错处理,防止脚本因某一个异常直接中断;
  • 代码结构优化:合并零散代码块,逻辑更清晰易维护。

内容的提问来源于stack exchange,提问作者Pynoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:27:27