1. # -*- coding: utf-8 -*-
2. # @Time : 2021/1/23
3. # @Author : 大海
4. import time
5. from functools import wraps
6. from selenium import webdriver
7. from selenium.common.exceptions import NoSuchElementException
8.
9. driver = webdriver.Chrome()
10. driver.get('https://baidu.com')
11.
12. # 获取当前时间
13. nowTime = time.strftime("%Y%m%d.%H.%M.%S")
14. file_path = './%s.png' % nowTime # 格式化字符串
15.
16.
17. # 装饰器
18. def screenshot(func):
19. @wraps(func)
20. def wrapper(*args, **kwargs):
21. try:
22. return func(*args, **kwargs)
23. except Exception as e:
24. driver.get_screenshot_as_file(file_path)
25. print(e)
26. finally:
27. driver.close()
28.
29. return wrapper
30.
31.
32. # 发生异常时截图
33. @screenshot
34. def screenshot_example():
35. driver.find_element_by_id('kw1').send_keys('selenium')
36.
37.
38. # 调用函数
39. screenshot_example()