用户希望能够突出显示网页上的一段内容(可以是任何他碰巧正在查看的网页),并将其复制到剪贴板,然后将其作为 markdown 格式保存到本地磁盘。
-
用户需要一种有效的方法来完成这项任务。
-
用户使用的是 Kubuntu 12.04,并希望使用 PySide。
-
用户没有 Python、Qt 或任何相关工具的经验,但他通过谷歌搜索发现 PySide 备受推荐,并且已经完成了一个 Hello World 教程。
-
用户目前使用了一种繁琐的方法:
- 突出显示部分并复制到剪贴板。
- 打开 Libre Office Writer。
- 粘贴到 Writer 中。
- 将 Writer 文档另存为 HTML。
- 打开终端。
- cd 到保存 HTML 的目录。
- pandoc -s -r html /home/me/a/b/mydoc.html -o /home/me/a/b/mydoc.md。
-
用户显然需要一种更好的方法!
-
用户的原始问题:https://unix.stackexchange.com/questions/78395/save-html-from-clipboard-as-markdown-text。
-
用户发现了一个可能的答案:https://stackoverflow.com/questions/15513159/getting-html-source-or-rich-text-from-the-x-clipboard。
-
上述内容促使用户在 Python 中实现此功能。
-
用户需要一个 KDE/PySide 版本的上述答案,它还包含 pandoc 转换到 markdown 的步骤。
-
除了用 KDE 剪贴板命令替换 gtk.Clipboard 命令外,这似乎完全没有问题。用户对此一无所知。
- 解决方案
- 通过支持 -t text/html(目标选择)和 pandoc 将 html 转换为 markdown 的最新版本的 xclip 即可完成此操作。
- 有关详细信息,请参阅:https://unix.stackexchange.com/questions/78395/save-html-from-clipboard-as-markdown-text
- 感谢 @mountainx 在 Unix 堆栈交换上再次提出问题,该问题提供了此解决方案,如上文的评论所述。
代码例子:
import subprocess
import tempfile
def get_html_from_clipboard():
"""Get HTML source from KDE clipboard."""
# Create a temporary file to store the HTML source.
with tempfile.NamedTemporaryFile(suffix=".html") as f:
# Copy the HTML source from the clipboard to the temporary file.
subprocess.call(["xclip", "-t", "text/html", "-selection", "clipboard", "-o"], stdout=f)
# Return the HTML source.
return f.read().decode("utf-8")
def convert_html_to_markdown(html):
"""Convert HTML to markdown."""
# Create a temporary file to store the markdown output.
with tempfile.NamedTemporaryFile(suffix=".md") as f:
# Convert the HTML source to markdown using pandoc.
subprocess.call(["pandoc", "-s", "-r", "html", "-i", "-", "md"], stdin=subprocess.PIPE, stdout=f, input=html.encode("utf-8"))
# Return the markdown output.
return f.read().decode("utf-8")
def save_markdown_to_file(markdown, filename):
"""Save markdown to file."""
# Open the file in write mode.
with open(filename, "w") as f:
# Write the markdown to the file.
f.write(markdown)
def main():
"""Main function."""
# Get the HTML source from the clipboard.
html = get_html_from_clipboard()
# Convert the HTML source to markdown.
markdown = convert_html_to_markdown(html)
# Save the markdown to a file.
save_markdown_to_file(markdown, "my_markdown_file.md")
if __name__ == "__main__":
main()