使用Selenium获取LinkedIn人员列表页用户profile href时重复返回相同URL
问题根因
- 选择器范围错误:
//a[@class='app-aware-link']是LinkedIn全站通用的a标签类,覆盖了导航栏、侧边推荐、广告、操作按钮等所有带链接的元素,没有限定在人员搜索结果的独立卡片容器内,抓取到的元素列表根本不是10个独立用户的profile链接 - 等待逻辑失效:仅等待
global-nav(全局导航栏)元素,该元素在搜索页跳转过程中始终存在,等导航栏渲染完成时,动态加载的搜索结果内容还未完全渲染,此时抓取到的元素多为未加载完成的占位DOM,所有元素绑定的href都是同一个默认值,自然会返回完全一致的10个URL - 无有效性校验:没有对抓取到的链接做过滤、去重,重复的无效链接会被直接追加到列表中
修正方案
核心调整两个逻辑:一是显式等待搜索结果容器加载完成,二是缩小选择器范围到单个结果卡片内部找链接,不要全局匹配。
修正后的代码示例:
try: browser.find_element_by_id("username").send_keys(email_address) sleep(1) browser.find_element_by_id("password").send_keys(password) sleep(1) browser.find_element_by_xpath("//button[@class='btn__primary--large from__button--floating']").click() # 等待登录完成,全局导航加载 element = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.ID, "global-nav"))) sleep(0.5) browser.get('https://www.linkedin.com/search/results/people/?geoUrn=%5B%22104246759%22%2C%2290009659%22%2C%22106383538%22%5D&keywords=mark%20johnson&origin=GLOBAL_SEARCH_HEADER') # 修正1:等待搜索结果卡片容器渲染完成,替代原有的过早抓取 WebDriverWait(browser, 15).until( EC.presence_of_element_located((By.CSS_SELECTOR, "li.reusable-search__result-container")) ) user = [] # 修正2:先定位所有独立的搜索结果卡片,再在每个卡片内部查找profile链接 result_cards = browser.find_elements_by_css_selector("li.reusable-search__result-container") # 遍历前10个有效卡片提取链接 for card in result_cards[:10]: # 限定在当前卡片范围内找带个人主页标识的链接,自动排除非profile的链接 profile_link = card.find_element_by_css_selector("a.app-aware-link[href*='/in/']") href = profile_link.get_attribute('href') # 简单去重过滤 if href and href not in user: user.append(href) print(user) except Exception as e: traceback.print_exc()
补充说明
- 选择器加
[href*='/in/']是因为LinkedIn所有个人profile的路径都包含/in/字段,能自动过滤掉导航、广告、其他跳转类的同标签a链接 - 尽量用显式等待替代固定
sleep(),LinkedIn动态加载速度受网络波动影响大,固定等待时间要么浪费时间,要么太早抓取拿不到渲染完成的元素 - 如果不需要链接附带的追踪参数(比如
?trk=xxx),可以用href.split('?')[0]清理为标准profile地址 - 旧版本Selenium的
find_element_by_*系列方法在Selenium 4中已逐步弃用,后续可以替换为基于By的定位方式提高兼容性
内容的提问来源于stack exchange,提问作者user14915996
相关产品推荐
相关产品推荐

