get_veri_code.py 2.4 KB

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