简体   繁体   English

Python从剪贴板下载URL

[英]Python download URL from clipboard

I am trying to download the URL that is contained in the clipboard, but i can not find a way to prevent downloading the same page over and over again. 我正在尝试下载剪贴板中包含的URL,但是我找不到防止重复下载同一页面的方法。 This is what i tried, but i get the error TypeError: 'int' object has no attribute '__getitem__' what does this mean? 这是我尝试过的方法,但是出现错误TypeError: 'int' object has no attribute '__getitem__'是什么意思? it say that the error is on line 13, this is where it checks to see if the URL is valid. 它说错误在第13行,在这里检查URL是否有效。

import time
import os
import urllib

basename = "page"
extension = ".html"
count=0
old_url = ""

while(1):
    time.sleep(1) #check clipboard every second
    clipboard = os.system("pbpaste") # get contents of clipboard
    if clipboard[:4] == "http" and clipboard != old_url: # check if valid URL and is diffrent
        while os.path.exists(basename+str(count)+extension): # Create new name
            count=count+1
        old_url = clipboard
        name=basename+str(count)+extension
        data=urllib.urlopen(clipboard).read() #get page data
        file(name, "wb").write(data) # write to file

The problem is on this line: 问题在这条线上:

clipboard = os.system("pbpaste")

Here's why: 原因如下:

In [3]: ?os.system
Type:       builtin_function_or_method
String Form:<built-in function system>
Docstring:
system(command) -> exit_status

Execute the command (a string) in a subshell.

os.system returns the exit status of the command, not the stdout of the command. os.system返回命令的退出状态 ,而不是命令的标准输出。

Try the subprocess module instead: 请尝试使用子流程模块:

import subprocess
clipboard = subprocess.check_output('pbpaste', shell=True)

Bear in mind, though, that it may be blank (or have less than five characters), which will cause your program to crash when you do clipboard[:4] . 但是请记住,它可能为空白(或少于五个字符),这将在您执行clipboard[:4]时导致程序崩溃。 Best practice is to check the length of a sliceable object before slicing it: if (len(clipboard) > 4) , or better yet, if (clipboard.startswith('http')) . 最佳实践是在切片对象之前检查其长度: if (len(clipboard) > 4) ,或者更好的是if (clipboard.startswith('http'))

Good luck and happy coding! 祝您好运,编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM