如何用Python Selenium定位LinkedIn收到的推荐详情元素?
LinkedIn推荐描述元素定位问题解决
问题背景
需要收集LinkedIn个人主页「收到的推荐」标签下的详细推荐描述段落,示例页面为LinkedIn个人推荐页(需登录账号查看)。现有代码尝试通过XPath定位元素,但descriptions变量始终为空,无法获取内容:
for index, row in df2.iterrows(): linkedin = row['LinkedIn Website'] current_url = f'{linkedin}/details/recommendations/' driver.get(current_url) time.sleep(random.uniform(2,3)) descriptions=driver.find_elements_by_xpath("//*[@class='display-flex align-items-center t-14 t-normal t-black']") s=0 for description in descriptions: s+=1 print(description.text) df2.loc[index, f'RecDescription_{str(s)}'] = description.text
正确元素定位方案
LinkedIn页面元素类名会频繁更新,原XPath使用的类名已失效,推荐以下两种稳定的定位方式:
方式1:基于元素层级的XPath定位
推荐描述属于「收到的推荐」卡片内的文本容器,可通过层级关系精准定位:
descriptions = driver.find_elements(By.XPATH, "//section[contains(@aria-label, 'Recommendations received')]//div[contains(@class, 'pv-recommendation-entity__text')]/p")
方式2:CSS选择器定位
CSS选择器在LinkedIn页面中兼容性更强,定位更稳定:
descriptions = driver.find_elements(By.CSS_SELECTOR, "[aria-label*='Recommendations received'] .pv-recommendation-entity__text p")
关键优化建议
- 替换固定延迟
time.sleep()为显式等待,确保元素完全加载:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 最长等待10秒,直到元素出现 descriptions = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.XPATH, "//section[contains(@aria-label, 'Recommendations received')]//div[contains(@class, 'pv-recommendation-entity__text')]/p")) ) - 确认页面默认显示的是「收到的推荐」标签,若打开的是「给出的推荐」,需先点击切换标签;
- 规避LinkedIn反爬机制,增加随机延迟,避免短时间内高频请求。
内容的提问来源于stack exchange,提问作者KDWB
相关产品推荐
相关产品推荐

