如何用Python从用户提供的Instagram链接提取账号用户名
Python提取Instagram个人主页链接对应用户名实现
直接用URL解析+规则匹配就能实现,不需要调用外部接口,兼容绝大多数常见的Instagram链接格式,同时能自动过滤帖子、Reels等非个人主页链接。
实现代码
import re from urllib.parse import urlparse def extract_instagram_username(url: str) -> str | None: # 解析输入链接,自动处理前后空格 parsed = urlparse(url.strip()) # 校验是否为Instagram官方域名,兼容带/不带www的情况 if not re.fullmatch(r'(www\.)?instagram\.com', parsed.netloc, re.IGNORECASE): return None # 拆分路径,过滤空字符串 path_segments = [seg for seg in parsed.path.strip('/').split('/') if seg] if not path_segments: return None # 排除非个人主页的固定路径前缀 non_profile_prefix = {'p', 'reel', 'reels', 'explore', 'tags', 'stories', 'accounts', 'direct', 'live'} candidate = path_segments[0] if candidate in non_profile_prefix: return None # 匹配Instagram用户名规则:仅允许字母、数字、下划线、点,长度1-30位 if re.fullmatch(r'[a-zA-Z0-9._]{1,30}', candidate): return candidate return None if __name__ == "__main__": input_link = input("请输入Instagram账号链接:") result = extract_instagram_username(input_link) if result: print(f"对应账号用户名:{result}") else: print("输入内容不是有效的Instagram个人主页链接")
兼容场景
- 带/不带www前缀、http/https协议的链接
- 链接末尾带多余斜杠、带语言参数、分享参数的情况
- 自动识别并拦截帖子、Reels短视频、话题页、私信页等非个人主页链接,避免误提取
测试示例
- 输入
https://www.instagram.com/instagram/?hl=en,输出对应账号用户名:instagram - 输入
https://instagram.com/meta,输出对应账号用户名:meta - 输入
https://www.instagram.com/p/Cz8xXxXxXxX/,输出输入内容不是有效的Instagram个人主页链接
内容的提问来源于stack exchange,提问作者Monke
相关产品推荐
相关产品推荐

