从 Excel 或 HTML 复制内容后,如何在 Python 中从剪贴板检索富文本格式内容?
我尝试了 pyperclip 和 Clipboard python 包,但它们只输出纯文本。
我希望Python能够直接输出富文本格式的内容,而不仅仅是纯文本内容。
没人回答,我参考pywin32中剪贴板的示例代码自己写一下。
Python 参考链接:https://gist.github.com/Erreinion/6691093
import win32clipboard
def GetAvailableFormats():
"""
Return a possibly empty list of formats available on the clipboard
"""
formats = []
try:
win32clipboard.OpenClipboard(0)
cf = win32clipboard.EnumClipboardFormats(0)
while (cf != 0):
formats.append(cf)
cf = win32clipboard.EnumClipboardFormats(cf)
finally:
win32clipboard.CloseClipboard()
return formats
# CF_HTML=49433
CF_HTML = win32clipboard.RegisterClipboardFormat("HTML Format")
if CF_HTML in GetAvailableFormats():
win32clipboard.OpenClipboard(0)
src = win32clipboard.GetClipboardData(CF_HTML)
src = src.decode("UTF-8")
print(src)
else:
print("No RTF content")