如何修复Instagram私信机器人Python代码中的JSONDecodeError
修复JSON解码错误及代码优化方案
一、核心问题:accounts.json格式不合法
报错json.decoder.JSONDecodeError: Expecting value: line 6 column 4 (char 90)说明你的infos/accounts.json文件在第6行第4列的位置存在JSON语法错误,常见情况包括:
- 键名未使用双引号(JSON强制要求双引号,单引号无效)
- 多余的逗号(比如最后一个账号对象末尾额外添加了逗号)
- 键值对不完整(只写了键名,缺冒号和对应的值)
- 大括号/中括号未闭合
正确的accounts.json格式示例
[ { "username": "你的账号1", "password": "你的密码1" }, { "username": "你的账号2", "password": "你的密码2" } ]
快速校验JSON格式的方法
用Python自带工具校验,命令行运行:
python -m json.tool infos/accounts.json
如果格式有问题,会直接提示错误位置和原因,无需依赖外部工具。
二、代码里的其他潜在问题(避免后续报错)
- 变量名重复错误:
原代码username = username.pop()这行存在变量名冲突,且应该从usernames列表中取数据,修改为:
username = usernames.pop()
- 文件读取不规范:
原代码直接用f = open()打开文件,改成with语句可自动关闭文件,更安全:
with open('infos/accounts.json', 'r') as f: accounts = json.load(f)
- 空列表防错:
循环中添加判断,避免usernames为空时执行pop()报错:
if not usernames: break
三、修复后的完整代码
import json import random from src.instadm import InstaDM from selenium.common.exceptions import NoSuchElementException # 规范读取accounts.json with open('infos/accounts.json', 'r') as f: accounts = json.load(f) with open('infos/usernames.txt', 'r') as f: usernames = [line.strip() for line in f] with open('infos/messages.txt', 'r') as f: messages = [line.strip() for line in f] while True: if not usernames: print('Finished usernames.') break dm_num = int(input('How many DM you want to send in each account: ')) for account in accounts: if not usernames: break # Auto login insta = InstaDM(username=account["username"], password=account["password"], headless=False) for i in range(dm_num): if not usernames: break # 修复变量名错误 username = usernames.pop() # Send message try: success = insta.sendMessage(user=username, message=random.choice(messages)) if not success: insta.teardown() continue except NoSuchElementException: # User not found = move on to the next user continue except Exception as e: if "timed out. Element not found with XPATH : //textarea[@placeholder]" in str(e): insta.teardown() continue # other error occured = move on to the next user #Log out insta.teardown()
内容的提问来源于stack exchange,提问作者jumidos
相关产品推荐
相关产品推荐

