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

Python Selenium无法获取LinkedIn指定class的a标签求助

LinkedIn职位页面元素定位失败的解决方案

尝试通过XPath、CSS选择器定位LinkedIn招聘页面中指定class的<a>标签时,始终返回空列表,无法获取目标元素。原代码如下:

import time

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(
    'https://www.linkedin.com/jobs/search/?currentJobId=3824897854&distance=25&f_E=1%2C2&f_TPR=r604800&f_WT=2&geoId=102221843&keywords=django%20developer&origin=JOB_SEARCH_PAGE_JOB_FILTER&refresh=true')
time.sleep(5)
i = 0
while i < 3:
    driver.execute_script('window.scrollTo(0,document.body.scrollHeight);')
    time.sleep(5)
    i += 1
jobs = driver.find_elements(By.XPATH, "//a[contains(@class,'ember-view job-card-container__link job-card-list__title')]")
print(jobs)
for job in jobs:
    print('1')
    text = job.get_attribute('label')
    if 'django developer' in text:
        print(text)
time.sleep(7)

问题原因及修复方案

  1. 等待策略不合理
    固定time.sleep()无法保证页面动态元素加载完成,LinkedIn职位列表为异步加载,需改用显式等待确保元素就绪。

  2. 滚动加载逻辑无效
    直接滚动到页面底部可能无法触发LinkedIn的职位加载机制,需滚动到当前最后一个职位卡片,触发后续内容加载。

  3. 元素定位条件过严
    原XPath使用完整class组合,LinkedIn部分class(如ember-view)为动态生成易变化,需简化定位条件,使用更稳定的class片段。

  4. 文本获取方式错误
    原代码尝试获取label属性,但LinkedIn职位标题文本直接包含在<a>标签内,应使用text属性获取。

修改后的代码

import time
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.get(
    'https://www.linkedin.com/jobs/search/?currentJobId=3824897854&distance=25&f_E=1%2C2&f_TPR=r604800&f_WT=2&geoId=102221843&keywords=django%20developer&origin=JOB_SEARCH_PAGE_JOB_FILTER&refresh=true')

# 显式等待职位列表区域加载完成
wait = WebDriverWait(driver, 15)
wait.until(ec.presence_of_element_located((By.CLASS_NAME, 'job-card-list')))

# 滚动加载更多职位,每次滚动到最后一个职位卡片
i = 0
while i < 3:
    job_cards = driver.find_elements(By.CLASS_NAME, 'job-card-container')
    if job_cards:
        # 滚动到最后一个职位卡片,触发加载
        driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth'});", job_cards[-1])
    time.sleep(3)
    i += 1

# 使用更稳定的CSS选择器定位职位标题<a>标签
jobs = driver.find_elements(By.CSS_SELECTOR, "a.job-card-list__title")
print(f"找到职位数量:{len(jobs)}")

for job in jobs:
    # 获取标签内的文本内容
    job_title = job.text.strip().lower()
    if 'django developer' in job_title:
        print(job_title)

time.sleep(7)
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:52:48