【发布时间】:2016-02-20 18:34:34
【问题描述】:
对 python 来说非常新,我正在尝试接受一个命令行参数,它是一个网站并将其设置为一个变量。我使用下面的行来执行此操作。
sitefile = ur.urlopen(sys.argv[1])
问题是它只有在命令行中完美格式化为“python filename.py http://mywebsite.com/contacts.html”时才有效。我希望能够删除 http://。我尝试了以下两种方法:
sitefile = ur.urlopen(sys.argv[1].startswith('http://'))
得到错误信息:AttributeError: 'bool' object has no attribute 'timeout'
sitefile = 'http://' + (ur.urlopen(sys.argv[1]))
收到错误消息:ValueError:未知 url 类型:'mywebsite.com/contacts.html'。它似乎只是忽略了这个 concat 的前半部分。
【问题讨论】:
-
阅读文档,
startswith不会像你想的那样做:sitefile = ur.urlopen('http://' + sys.argv[1]) -
startswith()如果字符串以 arg 开头,则返回布尔值,而不是您要查找的内容。您需要在传递给ur.urlopen()之前添加'http://。试试ur.urlopen('http://' + sys.argv[1]) -
非常感谢!