get_veri_code.py 2.7 KB

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