【问题标题】:python read and validate input url [duplicate]python读取并验证输入url [重复]
【发布时间】:2012-08-16 08:09:38
【问题描述】:

可能重复:
web2py url validator

你能帮我处理这段代码吗?

from urllib2 import Request, urlopen, URLError

url = raw_input('enter something')
req = Request(url)
try:
    response = urlopen(req)
except URLError, e:
    if hasattr(e, 'reason'):
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
    else:
        print 'URL is good!'

【问题讨论】:

  • 请编辑您的帖子并对其进行格式化以提高可读性 - 您尝试过什么?你的问题到底是什么?
  • 我想要求用户输入一个 url 然后验证它..
  • Traceback (most recent call last): File "C:/Users/r00t-7/PycharmProjects/untitled/sample.py", line 7, in <module> response = urlopen(req) File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 366, in open protocol = req.get_type() File "C:\Python25\lib\urllib2.py", line 241, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: www.google.com Process finished with exit code 1
  • 我认为您的 else 子句需要取消缩进。现在它只会打印“Url is good!”当出现 URLError 时。

标签: python url input


【解决方案1】:

如果您尝试从web2py url validator 实现代码,您会注意到您已经在不需要的地方添加并缩进了else。空格在 python 中很重要。我之前的答案中给出的代码是正确的,你只是复制不正确。你的代码应该是这样的(和我之前的回答一样):

from urllib2 import Request, urlopen, URLError

url = raw_input('enter something')
req = Request(url)
try:
    response = urlopen(req)
except URLError, e:
    if hasattr(e, 'reason'):
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    elif hasattr(e, 'code'):
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
else:
    print 'URL is good!'

else 子句是 try 的一部分,但不是异常测试的一部分。基本上,如果没有抛出异常,则 url 是有效的。如果你输入http://www.google.com,下面的代码会给你这个结果

python test.py 
enter somethinghttp://www.google.com
URL is good!

如果你输入http://www.google.com/bad,你会得到:

python test.py 
enter somethinghttp://www.google.com/bad
The server couldn't fulfill the request.
Error code:  404

【讨论】:

  • 我在python中用简洁的方式写了这个,现在我必须在web2py中使用它,这是我在你的帮助下编写的代码,谢谢大家,如果你认为它可以更好,请评论它,我爱你们..顺便说一句,因为我是stackoverflow的新手,我可以在4小时后发布我的答案..
  • 很高兴为您提供帮助。如果您的问题有正确答案,请务必选择它,以便帮助的人获得奖励。
  • 当然,但问题是我的声誉低于 15 岁 :)))
  • 您的代表不需要超过 15 岁即可接受答案,只需对问题或答案进行投票即可。要选择和回答,请参阅:meta.stackexchange.com/questions/5234/…
【解决方案2】:

尝试在您的输入中输入完整的 URL:

entersomething http://www.google.com

您需要指定请求的类型以便它理解正确处理它(在本例中为http)。

【讨论】:

  • 我知道但我想检查一下,我希望我的代码是友好的,用户只需输入它......我做的东西......
  • 啊,我的错误 - 我以为你在问为什么代码不起作用。很高兴您找到了答案!
【解决方案3】:

在 URL 前加上 http://

示例http://www.google.com

In [16]: response = urllib2.urlopen("http://www.google.com")

In [17]: response
Out[17]: <addinfourl at 28222408 whose fp = <socket._fileobject object at 0x01AE59B0>>

urllib2 模块定义了有助于在复杂世界中打开 URL(主要是 HTTP)的函数和类——基本和摘要身份验证、重定向、cookie 等等。

【讨论】:

  • 好吧,我试着用这种方式检查协议,有更好的主意吗? if url[0:7] == 'http://' or url[0:8] == 'https://' or url[0:6] =='ftp://': [do something with url..]
【解决方案4】:

您提供的堆栈显示您遇到了 ValueError

"C:\Python25\lib\urllib2.py", line 241, in get_type raise ValueError, "unknown url type: %s" % self.__original ValueError: unknown url type: www.google.com

所以你可以为 ValueError 添加另一个 except 子句来通知用户 url 无效。

或者如果您打算更正该网址,请使用url.lower().startswith('http://') or ...

还请注意,urlopen 可能会引发许多其他异常,因此您可能还想捕获一个通用的Exception。你可以找到更详细的讨论here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多