2

重複の可能性:
web2pyurlバリデーター

このコードを手伝ってくれませんか?

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!'
4

4 に答える 4

3

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 except の一部であり、例外テストの一部ではありません。基本的に例外がスローされない場合、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
于 2012-08-16T11:01:23.823 に答える
2

入力に完全な URL を入力してみてください。

entersomething http://www.google.com

リクエストが適切に処理されることを理解するには、リクエストのタイプを指定する必要があります (この場合はhttp)。

于 2012-08-16T08:17:31.857 に答える
0

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 モジュールは、基本認証とダイジェスト認証、リダイレクト、Cookie など、複雑な世界で URL (主に HTTP) を開くのに役立つ関数とクラスを定義します。

于 2012-08-16T08:17:30.940 に答える
0

提供したスタックは、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を修正する場合は、url.lower().startswith('http://') or ...

また、urlopen は他の多くの例外をスローする可能性があるため、ジェネリックもキャッチする必要がある場合があることに注意してくださいExceptionここでより詳細な議論を見つけることができます

于 2012-08-16T11:21:01.507 に答える