用 Python 解析结构化的 LinkedIn 个人资料 JSON,先读取 status,再把 profile 当作键集合固定的 dict 来处理:用 TypedDict 描述它,检查值是否为 None、列表是否为 [],用一个小辅助函数转换 "2014" 和 "2014-02" 这样的日期,需要表格时再用 pandas.json_normalize 把 experience 列表扁平化。ProfileHunt 对每份个人资料都返回相同的键,所以同一个解析器既能处理有三十段经历的 CEO,也能处理几乎什么都不显示的个人资料。
本文只讲解析。想了解个人资料 API 做什么、JSON 为什么长这样,请先看什么是 LinkedIn 个人资料 API。
要点速览
- 先检查外层结构,再读个人资料。 只要
status是gone或unavailable,profile就是None。 - 键永远不会缺失。 用
profile["headline"]并检查是否为None;.get()会掩盖真正的 bug。 - 职位日期是不完整的。
"2014"和"2014-02"不是完整日期;转换时要保留它们的精度。 - 当前职位就是
end_date is None。 一份个人资料可能有多个,所以要返回列表。 json_normalize会丢掉没有职位的人。 要把扁平化后的表重新合并回个人资料列表。
你要解析的是什么
POST https://api.profilehunt.dev/v1/profile 的响应是一个包含两个键的外层结构:status 和 profile。当 status 为 "ok" 时,profile 中是数据。当它为 "gone"(该 URL 下没有公开个人资料)或 "unavailable"(LinkedIn 当时没有返回该资料)时,profile 为 None,也不消耗点数。
profile 内部的键可以分为几组:
| 分组 | 键 | Python 类型 |
|---|---|---|
| 身份 | public_id、profile_url、full_name、first_name、last_name、photo_url | str,姓名和照片可能为 None |
| 概要 | headline、about、location、country | str 或 None |
| 职业 | experience、education | list[dict],可能为 [] |
| 信号 | followers、connections、creator、badges、languages | int 或 None、bool、list[str] |
| 动态 | last_post_at、recent_posts、recent_articles | ISO 8601 str 或 None、list[dict] |
| 点赞与评论 | last_reaction_at、recent_reactions、last_comment_at、recent_comments、last_active_at | ISO 8601 str 或 None、list[dict] |
| 元数据 | scraped_at | ISO 8601 str |
LinkedIn 个人资料 JSON 结构指南解释了每个字段。这里我们把它们转换成可以放心使用的 Python 值。
用 Python 逐步解析个人资料
示例使用 ProfileHunt 首页上的两份真实示例响应:Bill Gates 和 Satya Nadella。
步骤 1:先读外层结构,再读个人资料
data = res.json()
if data["status"] != "ok":
# "gone":没有公开个人资料。"unavailable":稍后再试。两者都不收费。
handle_miss(data["status"])
else:
profile = data["profile"]
跳过这个检查是最常见的解析 bug。遇到第一个找不到的个人资料时,data["profile"]["full_name"] 就会抛出 TypeError: 'NoneType' object is not subscriptable。Python 数据补全示例展示了包裹这段代码的完整请求。
步骤 2:用 TypedDict 描述数据结构
TypedDict 能给你编辑器补全和类型检查,而不改变数据本身:res.json() 返回的 dict 可以原样使用。
from typing import Literal, TypedDict
class Position(TypedDict):
company: str
company_url: str | None
title: str | None # 仅当前职位有值
location: str | None
description: str | None
start_date: str | None # "2014" 或 "2014-02"
end_date: str | None # 当前职位为 None
class School(TypedDict):
school: str
school_url: str | None
start_date: str | None
end_date: str | None
class Post(TypedDict):
url: str
posted_at: str
text: str | None
likes: int | None
class Article(TypedDict):
url: str
headline: str | None
image_url: str | None
published_at: str
likes: int | None
class Reaction(TypedDict):
verb: str # 互动类型,沿用 LinkedIn 的标签
reacted_at: str # ISO 8601 UTC
post_url: str | None
post_author: str | None # 从帖子 URL 中取得的个人资料名称
post_at: str | None
class Comment(TypedDict):
verb: str # "commented on a post" 或 "replied to a comment"
text: str | None
age: str # 与 LinkedIn 显示的一致:"5h"、"3d"、"2w"、"4mo"、"1y"
commented_at: str | None # 近似值:从 scraped_at 往前推算 age
post_url: str | None
post_author: str | None
post_at: str | None # 精确值
class Profile(TypedDict):
public_id: str
profile_url: str
full_name: str | None
first_name: str | None
last_name: str | None
photo_url: str | None
headline: str | None
about: str | None
location: str | None
country: str | None
experience: list[Position]
education: list[School]
languages: list[str]
followers: int | None
connections: int | None
creator: bool
badges: list[str]
last_post_at: str | None
recent_posts: list[Post]
recent_articles: list[Article]
last_reaction_at: str | None
recent_reactions: list[Reaction]
last_comment_at: str | None # 近似值,与 commented_at 相同
recent_comments: list[Comment]
last_active_at: str | None # last_post_at、last_reaction_at、last_comment_at 中最新的一个
scraped_at: str
class ProfileResponse(TypedDict):
status: Literal["ok", "gone", "unavailable"]
profile: Profile | None
str | None 语法需要 Python 3.10 或更高版本。这就是 API 返回的全部键。OpenAPI 文件描述的是同一个 Profile 对象,所以你也可以自动生成这些类型,而不必手动维护。
步骤 3:把 None 和 [] 当作数据
None 表示该个人资料没有向未登录访客显示这个值。它不是错误。两条规则可以防止它泄漏到你的输出里:
name = profile["full_name"] or profile["public_id"] # 显示用的后备值
headline = profile["headline"] or "" # 文本列用空字符串
has_posts = bool(profile["recent_posts"]) # [] 为假值
followers = profile["followers"] # 保留 None;写成 0 就是在撒谎
数字要保留为 None,而不是 0。followers: None 的个人资料只是没有显示数量;关注者为 0 的个人资料是另一回事。还要记住,在公开视图中 connections 最多到 500,所以 500 表示“500 或以上”。
步骤 4:解析年份和年月日期
职位和学校的日期是 LinkedIn 显示的字符串:Bill Gates 在 Gates Foundation 的是 "2000",Satya Nadella 在 Microsoft 的是 "2014-02"。把它们转换成 date,并在旁边记录精度:
from datetime import date, datetime
def parse_ym(value: str | None) -> tuple[date | None, str | None]:
"""'2014' -> (date(2014, 1, 1), 'year'); '2014-02' -> (date(2014, 2, 1), 'month')."""
if value is None:
return None, None
if len(value) == 4:
return date(int(value), 1, 1), "year"
year, month = value.split("-")
return date(int(year), int(month), 1), "month"
def parse_ts(value: str | None) -> datetime | None:
"""UTC 的 ISO 8601,例如 '2026-10-11T03:45:31.389Z'。"""
return datetime.fromisoformat(value) if value else None
parse_ts 在 Python 3.11 及以上版本中可以直接使用。在 3.10 及更早版本中,fromisoformat 不接受末尾的 Z,请改用 datetime.fromisoformat(value.replace("Z", "+00:00"))。

步骤 5:挑出当前职位
def current_roles(profile: Profile) -> list[Position]:
return [p for p in profile["experience"] if p["end_date"] is None]
在示例数据上,它为 Bill Gates 返回三个职位(Gates Foundation、Breakthrough Energy、Microsoft),为 Satya Nadella 返回两个(Microsoft 和 University of Chicago 的董事会席位)。第一项通常是主要工作,但只返回一个职位的函数会悄悄丢掉其余的。过往职位返回的是 title: None,因为公开视图只显示当前职位的头衔。
用 pandas json_normalize 扁平化工作经历
pandas.json_normalize 会把嵌套列表变成每个职位一行,并通过 meta 把个人资料层级的键复制到每一行上:
import pandas as pd
roles = pd.json_normalize(
profiles, # 个人资料 dict 组成的列表
record_path="experience",
meta=["public_id", "full_name", "scraped_at"],
)
roles["is_current"] = roles["end_date"].isna()
roles["start_year"] = roles["start_date"].str[:4].astype("Int64")
对这两份示例个人资料,结果是八行:
| public_id | company | title | start_year | is_current |
|---|---|---|---|---|
| williamhgates | Gates Foundation | Co-chair | 2000 | True |
| williamhgates | Breakthrough Energy | Founder | 2015 | True |
| williamhgates | Microsoft | Co-founder | 1975 | True |
| satyanadella | Microsoft | Chairman and CEO | 2014 | True |
| satyanadella | University of Chicago | Member Board Of Trustees | 2018 | True |
| satyanadella | Starbucks | NaN | 2017 | False |
| satyanadella | The Business Council U.S. | NaN | 2021 | False |
| satyanadella | Fred Hutch | NaN | 2016 | False |
如果要每人一行,用 pd.json_normalize(profiles, max_level=0):标量键变成列,列表保留在 object 列中。对 education 或 recent_posts 这些列表,用 record_path="education" 或 "recent_posts" 做同样的处理。
解析个人资料 JSON 时,大多数教程搞错了什么
到处都用 .get()。 profile.get("headline", "") 看起来很稳妥,但每个键始终存在,所以 .get() 只会掩盖拼写错误。profile.get("headlnie") 会永远返回默认值,而不是在第一次运行时就报错。
用 strptime("%Y-%m") 解析日期。 它遇到只有年份的日期就会失败,而示例中大多数职位日期都只有年份。一个格式字符串无法同时处理两种形式。
把 experience[0] 当作当前工作。 experience[0] 可能是已经结束的职位,而且很多个人资料的当前职位不止一个。请按 end_date is None 过滤。
以为 pandas 中 NaN 和 None 的行为一样。 经过 json_normalize 后,像 description 这样全为空的列存的是 None,而像 title 这样有值有空的列存的是 NaN。请用 pd.isna() 判断,绝不要用 == None。
误区与事实
| 误区 | 事实 |
|---|---|
| 值缺失说明 API 调用失败了。 | 查询失败时 status 不是 "ok"。在 "ok" 的个人资料中出现 None,只说明这个值没有公开显示。 |
connections: 500 是精确数量。 | 它表示 500 或以上;公开视图设有上限。衡量影响力请用 followers。 |
| 过往职位有可以解析的头衔。 | 公开视图只显示当前职位的头衔,所以过往职位是 title: None。 |
json_normalize 会保留每一个人。 | 使用 record_path 时,experience 为 [] 的个人资料不会产生任何行,会从表中消失。 |
| 必须用 pydantic 才能安全解析。 | TypedDict 加几个辅助函数就够了。需要接收不可信输入时再用校验库,面对稳定的 schema 则不必。 |

进阶:边界处用类型化模型,存储中保留原始 JSON
基础功能跑通后,有三个习惯能让解析器随着数据管道的增长保持稳定。
存储原始响应,其余一切由它推导。 把未经改动的 profile dict 写入一个 JSON 列或 JSONL 文件,以 public_id 和 scraped_at 为键。这样你的扁平表就成了一个可以随时重跑的函数。下个季度你决定需要 education 或 recent_articles 时,可以直接从存储中重建,而不必花钱重新获取。
在一个地方转换成你自己的模型。 如果你的应用需要一个带 title、company 和 started 字段的 Contact dataclass,就写一个把 Profile 映射过去的函数,下游只用它。字段取舍(哪个当前职位优先、只有年份的日期如何处理)就都集中在一处。
from dataclasses import dataclass
@dataclass
class Contact:
public_id: str
name: str | None
title: str | None
company: str | None
started: date | None
started_precision: str | None
def to_contact(profile: Profile) -> Contact:
roles = current_roles(profile)
main = roles[0] if roles else None
started, precision = parse_ym(main["start_date"]) if main else (None, None)
return Contact(
public_id=profile["public_id"],
name=profile["full_name"],
title=main["title"] if main else None,
company=main["company"] if main else None,
started=started,
started_precision=precision,
)
用 public_id 关联,而不是用姓名。 人会重名,但个人资料 URL 不会重复。把扁平化的职位表合并回每人一行的表时,以 public_id 为键,从个人表做左连接,就能保留没有职位的个人资料。
留意新增的键,但不要因此崩溃。 TypedDict 在运行时不会拒绝多余的键,所以新字段永远不会让解析器崩溃。如果你想知道何时出现了新字段,可以在测试中比较 set(profile) 和 Profile.__annotations__,并记录差异。
ProfileHunt 的定位
ProfileHunt 是一个 LinkedIn 个人资料 API:输入公开个人资料 URL,输出上面这样的 JSON。每份个人资料的 schema 都相同,个人资料没有显示的内容用 None 和 [] 表示,所以像上面这样的小型解析器就足够了。每次查询都实时读取公开个人资料,scraped_at 会准确告诉你读取时间。
它只返回公开视图:没有电子邮件或电话号码,没有过往职位的头衔,connections 上限为 500。价格是每找到 1,000 份个人资料 0.50 美元,未找到的个人资料不收费。
开始使用
在注册页面用工作邮箱创建密钥,即可获得 100 个免费点数;按照快速入门完成第一次调用,编写类型时把个人资料端点参考放在手边。要在整份列表上运行这个解析器,用 Python 大规模补全个人资料的工作流介绍了批次、轮询和检查点。同样的解析在 TypeScript 中怎么做,请看在 JavaScript 中解析个人资料响应。想了解全局,请看什么是 LinkedIn 个人资料 API。
常见问题
如何把 LinkedIn 个人资料 JSON 转换成 pandas DataFrame?
用 pd.json_normalize(profiles, max_level=0) 得到每人一行,用 pd.json_normalize(profiles, record_path="experience", meta=["public_id"]) 得到每个职位一行。两者按 public_id 关联。
为什么我的 Python 代码报错 'NoneType' object is not subscriptable?
你在 status 为 gone 或 unavailable 时读取了 data["profile"],此时 profile 是 None。在读取任何个人资料字段之前,先检查 data["status"] == "ok"。
如何在 Python 中解析 "2014-02" 这样的 LinkedIn 日期?
按短横线拆分:四个字符是年份,七个字符是年和月。转换成 date(year, month or 1, 1),并记录它是否只有年份,就像上面的 parse_ym 辅助函数那样。
如何在 LinkedIn 个人资料 JSON 中找到某人的当前工作?
取出 experience 中 end_date 为 None 的条目。可能不止一条;第一条通常是主要职位。
LinkedIn 个人资料数据应该用 pydantic 还是 TypedDict?
数据来自稳定的 API、而你只需要类型提示时,TypedDict 就够了。需要运行时校验或类型转换时再用 pydantic,比如 JSON 来自人工编辑的文件。


