get_email_code.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from DrissionPage.common import Keys
  2. import time
  3. import re
  4. from config import Config
  5. class EmailVerificationHandler:
  6. def __init__(self, browser, mail_url="https://tempmail.plus"):
  7. self.browser = browser
  8. self.mail_url = mail_url
  9. self.username = Config().get_temp_mail()
  10. def get_verification_code(self):
  11. code = None
  12. try:
  13. print("正在处理...")
  14. # 打开新标签页访问临时邮箱
  15. tab_mail = self.browser.new_tab(self.mail_url)
  16. self.browser.activate_tab(tab_mail)
  17. # 输入用户名
  18. self._input_username(tab_mail)
  19. # 等待并获取最新邮件
  20. code = self._get_latest_mail_code(tab_mail)
  21. # 清理邮件
  22. self._cleanup_mail(tab_mail)
  23. # 关闭标签页
  24. tab_mail.close()
  25. except Exception as e:
  26. print(f"获取验证码失败: {str(e)}")
  27. return code
  28. def _input_username(self, tab):
  29. while True:
  30. if tab.ele("@id=pre_button"):
  31. tab.actions.click("@id=pre_button")
  32. time.sleep(0.5)
  33. tab.run_js('document.getElementById("pre_button").value = ""')
  34. time.sleep(0.5)
  35. tab.actions.input(self.username).key_down(Keys.ENTER).key_up(Keys.ENTER)
  36. break
  37. time.sleep(1)
  38. def _get_latest_mail_code(self, tab):
  39. code = None
  40. while True:
  41. new_mail = tab.ele("@class=mail")
  42. if new_mail:
  43. if new_mail.text:
  44. tab.actions.click("@class=mail")
  45. break
  46. else:
  47. break
  48. time.sleep(1)
  49. if tab.ele("@class=overflow-auto mb-20"):
  50. email_content = tab.ele("@class=overflow-auto mb-20").text
  51. verification_code = re.search(
  52. r"verification code is (\d{6})", email_content
  53. )
  54. if verification_code:
  55. code = verification_code.group(1)
  56. print("马上就要成功了")
  57. else:
  58. print("执行失败")
  59. return code
  60. def _cleanup_mail(self, tab):
  61. if tab.ele("@id=delete_mail"):
  62. tab.actions.click("@id=delete_mail")
  63. time.sleep(1)
  64. if tab.ele("@id=confirm_mail"):
  65. tab.actions.click("@id=confirm_mail")