使用Python Instaloader爬取Instagram时遭遇HTTP 401错误求助
解决Instaloader出现ConnectionException: HTTP 401错误的方案
错误原因
HTTP 401代表未授权访问,Instagram对未登录的API请求有严格的频率限制,批量请求几次后就会触发限制导致请求被拒绝。另外,目标帖子设为私有、已删除,或者会话过期也会引发该错误。
具体解决方案
1. 登录Instagram账号
登录后能大幅提升请求限额,避免触发未授权限制。可以直接在代码中登录,或者加载已保存的会话文件(推荐,避免重复输入密码):
直接登录示例:
import instaloader L = instaloader.Instaloader() # 替换为你的Instagram账号和密码 L.login("your_username", "your_password") for shortcode in shortcodes.values(): try: post = instaloader.Post.from_shortcode(L.context, shortcode) L.download_post(post, target=post.owner_username) except Exception as e: print(f"处理短代码{shortcode}时出错: {e}")
加载已保存的会话(首次登录后会生成会话文件):
import instaloader L = instaloader.Instaloader() username = "your_username" try: # 尝试加载已保存的会话 L.load_session_from_file(username) except FileNotFoundError: # 首次登录,保存会话到文件 L.login(username, "your_password") L.save_session_to_file() for shortcode in shortcodes.values(): try: post = instaloader.Post.from_shortcode(L.context, shortcode) L.download_post(post, target=post.owner_username) except Exception as e: print(f"处理短代码{shortcode}时出错: {e}")
2. 添加请求延迟
批量操作时,过快的请求会触发反爬机制,在循环中加入随机延迟:
import instaloader import time import random L = instaloader.Instaloader() L.login("your_username", "your_password") for shortcode in shortcodes.values(): try: post = instaloader.Post.from_shortcode(L.context, shortcode) L.download_post(post, target=post.owner_username) # 添加2-5秒的随机延迟 time.sleep(random.uniform(2, 5)) except Exception as e: print(f"处理短代码{shortcode}时出错: {e}") # 出错后延长延迟再重试 time.sleep(10)
3. 捕获并处理401异常
针对401错误单独处理,支持重试或跳过无效帖子:
import instaloader import time from instaloader.exceptions import ConnectionException L = instaloader.Instaloader() L.login("your_username", "your_password") for shortcode in shortcodes.values(): retry_count = 3 while retry_count > 0: try: post = instaloader.Post.from_shortcode(L.context, shortcode) L.download_post(post, target=post.owner_username) break except ConnectionException as e: if "401" in str(e): retry_count -= 1 print(f"短代码{shortcode}请求401,剩余重试次数{retry_count}") time.sleep(15) else: print(f"连接错误: {e}") break except Exception as e: print(f"其他错误: {e}") break
4. 检查短代码有效性
确保所有短代码对应的帖子是公开且存在的:私有帖子需要你有权限访问(即已关注该用户),否则会返回401。如果是无权访问的私有帖子,要么关注该用户,要么直接跳过这类短代码。
内容的提问来源于stack exchange,提问作者complog
相关产品推荐
相关产品推荐

