好吧,我对python还不太熟悉,我正在制作一个控制台,它将允许多个特性,其中一个特性是获取一个页面源并将其打印到页面上,或者如果它们有另一个arg,则命名该arg的文件。。。第一个参数将是从中获取源的网站url。
我的进口产品是:
import os, urllib.request
这是我的代码:
def grab(command, args, argslist):
if args == "":
print("The " + command + " command wan't used correctly type help " + command + " for help...")
if args != "":
print("This may take a second...")
try:
argslistcheck = argslist[0]
if argslistcheck[0:7] != "http://":
argslist[0] = "http://" + argslist[0]
with urllib.request.urlopen(argslist[0]) as url:
source = url.read()
source = str(source, "utf-8")
except IndexError:
print("Couln't connect")
source = ""
try:
filesourcename = argslist[1] + ".txt"
filesourceopen = open(filesourcename, "w")
filesourceopen.write(source)
filesourceopen.close()
print("You can find the file save in " + os.getcwd() + " named " + argslist[1] + ".txt.")
except IndexError:
print(source)
现在,虽然我现在可以改进我的代码,但我将重点放在要点上。现在它工作了,我稍后会改进代码,唯一的问题是如果用户输入一个假的网站或一个不存在的网站页面,那么它会返回很多错误。但如果我改变:
except IndexError:
print("Coulnd't connect")
source = ""
只是:
except:
print("Couldn't connect")
source = ""
然后它总是说无法连接。。。
有什么帮助吗?我没有把剩下的代码放进去,因为我觉得它没有用,如果你需要的话,我可以把它全部放进去。
我之所以将这个隐藏错误命名为hide error,是因为它仍然工作,因为它只是说它无法连接,如果用户键入第二个参数,那么它将把源保存到他命名的文件中。
目前没有回答
相关问题 更多 >
编程相关推荐