如何从剪贴板获取HTML源代码或富文本?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (89)

如何从剪贴板获取富文本或HTML源代码?例如,如果从Web浏览器复制一些文本并将其粘贴到Kompozer中,则它将粘贴为HTML,并保留链接等。但是,对于相同的选择,xclip -o只输出纯文本,重新格式化的方式类似于elinks -dump。我想将HTML拉出并放入文本编辑器(特别是vim)。

我现在选择的语言是Python。

提问于
用户回答回答于

在X11中,必须与选择所有者沟通,询问支持的格式,然后以特定格式请求数据。我认为最简单的方法是使用现有的窗口工具包。例如。与Python和GTK:

#!/usr/bin/python

import glib, gtk

def test_clipboard():
    clipboard = gtk.Clipboard()
    targets = clipboard.wait_for_targets()
    print "Targets available:", ", ".join(map(str, targets))
    for target in targets:
        print "Trying '%s'..." % str(target)
        contents = clipboard.wait_for_contents(target)
        if contents:
            print contents.data

def main():
    mainloop = glib.MainLoop()
    def cb():
        test_clipboard()
        mainloop.quit()
    glib.idle_add(cb)
    mainloop.run()

if __name__ == "__main__":
    main()

输出将如下所示:

$ ./clipboard.py 
Targets available: TIMESTAMP, TARGETS, MULTIPLE, text/html, text/_moz_htmlcontext, text/_moz_htmlinfo, UTF8_STRING, COMPOUND_TEXT, TEXT, STRING, text/x-moz-url-priv
...
Trying 'text/html'...
I asked <a href="http://superuser.com/questions/144185/getting-html-source-or-rich-text-from-the-x-clipboard">the same question on superuser.com</a>, because I was hoping there was a utility to do this, but I didn't get any informative responses.
Trying 'text/_moz_htmlcontext'...
<html><body class="question-page"><div class="container"><div id="content"><div id="mainbar"><div id="question"><table><tbody><tr><td class="postcell"><div><div class="post-text"><p></p></div></div></td></tr></tbody></table></div></div></div></div></body></html>
...
Trying 'STRING'...
I asked the same question on superuser.com, because I was hoping there was a utility to do this, but I didn't get any informative responses.
Trying 'text/x-moz-url-priv'...
http://stackoverflow.com/questions/3261379/getting-html-source-or-rich-text-from-the-x-clipboard
用户回答回答于

已经存在一个命令:xclip。假设操作系统像Debian一样附带颠覆性的头部xclip

要列出CLIPBOARD选择的目标:

$ xclip -selection clipboard -o -t TARGETS
TIMESTAMP
TARGETS
MULTIPLE
SAVE_TARGETS
text/html
text/_moz_htmlcontext
text/_moz_htmlinfo
UTF8_STRING
COMPOUND_TEXT
TEXT
STRING
text/x-moz-url-priv

要选择一个特定的目标:

$ xclip -selection clipboard -o -t text/html
 <a href="https://stackoverflow.com/users/200540/rkhayrov" title="3017 reputation" class="comment-user">rkhayrov</a>
$ xclip -selection clipboard -o -t UTF8_STRING
 rkhayrov
$ xclip -selection clipboard -o -t TIMESTAMP
684176350

xclip可以设置和拥有一个选择(-i而不是-o)。

扫码关注云+社区

领取腾讯云代金券