使用Python Selenium获取LinkedIn个人资料列表的当前职位信息
问题根因
find_elements_by_class_name方法仅支持传入单个类名,你传入了由空格拼接的两个类名linked-area flex-1,无法命中对应DOM元素,所以返回空列表。- 现有代码仅提取了元素全文,没有做
Current:之后到Summary:之前的内容截取,定位成功后需要补充对应逻辑。
修复方案
步骤1:正确定位元素
推荐使用CSS选择器来匹配多类名元素,新版Selenium建议统一使用By类来指定定位方式,示例代码如下:
首先导入依赖:
from selenium.webdriver.common.by import By
替换原来的元素定位代码:
# 旧版本Selenium也可以直接用 browser.find_elements_by_css_selector('.linked-area.flex-1.cursor-pointer') currentDesignations = browser.find_elements(By.CSS_SELECTOR, '.linked-area.flex-1.cursor-pointer')
步骤2:截取目标内容
遍历元素时,对提取到的文本做切割处理,拿到目标区间的内容:
currentDsgn = [] for currentDesignation in currentDesignations: full_text = currentDesignation.text.strip() if 'Current:' in full_text: content_after_current = full_text.split('Current:')[1] if 'Summary:' in content_after_current: target_content = content_after_current.split('Summary:')[0].strip() else: target_content = content_after_current.strip() currentDsgn.append(target_content) print(currentDsgn)
额外排查点
如果修改后还是返回空列表,可检查两种常见情况:
- 页面未完全加载就执行了定位逻辑,可添加显式等待等待目标元素渲染完成
- 目标元素在iframe内,需要先切换到对应iframe再执行定位
内容的提问来源于stack exchange,提问作者ShridharK
相关产品推荐
相关产品推荐

