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

如何用Selenium点击LinkedIn中XPath、类名相同的多个展开按钮

问题背景

点击LinkedIn页面按钮时遇到问题:包含大量工作经历、教育背景、证书资质信息的个人主页,需要点击「Show more」按钮才能展开全部内容。

尝试过通过XPath检索元素后循环点击页面所有按钮,但未生效,因为Selenium检索到的按钮class和其他元素完全一致。
目前已知可以成功点击工作经历模块第一个展开按钮的代码如下:

self.driver.execute_script("arguments[0].click();", WebDriverWait(
            self.driver, 3).until(EC.element_to_be_clickable((By.XPATH, "//li-icon[@class='pv-profile"
                                                                        "-section__toggle-detail-icon']"))))

但该方法无法定位教育背景、证书资质模块的按钮,临时解决方案是匹配元素内文本点击,代码如下:

self.driver.find_element_by_xpath("//*[contains(text(), 'Pokaż więcej')]").click()

或

self.driver.find_element_by_xpath("//*[contains(text(), 'Pokaż 1 uczelnię więcej')]").click()

该方案需要匹配不同语言的按钮文本,局限性极大。

最优解决方案

所有模块的展开按钮均带有pv-profile-section__toggle-detail-icon固定特征类,无需区分模块所属、无需匹配文本,直接检索所有符合该特征的元素依次点击即可,兼容性更强。

containers = self.driver.find_elements_by_xpath("//li-icon[@class='pv-profile-section__toggle-detail-icon']")
for button in containers:
    self.driver.execute_script('arguments[0].click()', button)

优化建议

可增加显式等待,避免页面未渲染完成导致漏点按钮,优化后代码如下:

# 等待所有展开按钮加载完成
WebDriverWait(self.driver, 5).until(EC.presence_of_all_elements_located((By.XPATH, "//li-icon[@class='pv-profile-section__toggle-detail-icon']")))
# 批量点击所有展开按钮
containers = self.driver.find_elements_by_xpath("//li-icon[@class='pv-profile-section__toggle-detail-icon']")
for button in containers:
    self.driver.execute_script('arguments[0].click()', button)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:15:00