instagrapi.exceptions.UnknownError 确认码

问题描述 投票:0回答:1

我刚开始使用 instagrapi,我想了解是否有办法自动执行确认码过程。

from instagrapi import Client

cl = Client()
cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)

user_id = cl.user_id_from_username("adw0rd")
medias = cl.user_medias(user_id, 20)

每次运行代码时,都需要发送到我的电子邮件的验证码。这对于我想要制作的应用程序来说是不可持续的。

python web-scraping instagram instagrapi
1个回答
0
投票

您不应该每次都尝试登录,这不是人类行为,并且说租赁是可疑的 - 始终尝试使用存储的会话信息登录。 这是 API 文档中的一个示例;首次登录:

from instagrapi import Client

cl = Client()
cl.login(USERNAME, PASSWORD)
cl.dump_settings("session.json")

下次登录时:

from instagrapi import Client

cl = Client()
cl.load_settings("session.json")
cl.login (USERNAME, PASSWORD) # this doesn't actually login using username/password but uses the session
cl.get_timeline_feed() # check session

这样您就可以防止 Instagram 每次都要求您输入验证码。有关此内容和最佳实践的更多信息: https://subzeroid.github.io/instagrapi/usage-guide/best-practices.html

现在,在提取验证码时,您可以简单地捕获异常“ChallengeRequired”并使用电子邮件和 imaplib 库来处理它,如下所示:

def get_code_from_email(username):

            mail = imaplib.IMAP4_SSL('outlook.office365.com')
            mail.login(email_user, email_password)
            mail.select("inbox")
            result, data = mail.search(None, "(UNSEEN)")
            assert result == "OK", "Error1 during get_code_from_email: %s" % result
            ids = data.pop().split()
            for num in reversed(ids):
                mail.store(num, "+FLAGS", "\\Seen")  # mark as read
                result, data = mail.fetch(num, "(RFC822)")
                assert result == "OK", "Error2 during get_code_from_email: %s" % result
                msg = email.message_from_string(data[0][1].decode())
                payloads = msg.get_payload()
                if not isinstance(payloads, list):
                    payloads = [msg]
                code = None
                for payload in payloads:
                    body = payload.get_payload(decode=True).decode()
                    if "<div" not in body:
                        continue
                    match = re.search(">([^>]*?({u})[^<]*?)<".format(u=username), body)
                    if not match:
                        continue
                    print("Match from email:", match.group(1))
                    match = re.search(r">(\d{6})<", body)
                    if not match:
                        print('Skip this email, "code" not found')
                        continue
                    code = match.group(1)
                    if code:
                        return code
            return False

处理程序中的这段代码应该可以解决问题。太了解如何在代码中实现它,请参阅此处: https://subzeroid.github.io/instagrapi/usage-guide/challenge_resolver.html

祝你好运:)

© www.soinside.com 2019 - 2024. All rights reserved.