python urllib2 ×¥È¡ÍøÒ³ ÈçºÎ²¶»ñ¸÷ÖÖÒì³£ÄØ
ÎÒÓÃpythonµÄ urllib2À´×¥È¡ÍøÒ³ Ôõô²ÅÄܲ¶»ñ¸÷ÖÖ·µ»ØµÄÒì³£ÄØ?
ÓÐÈçÏ´úÂë:
Python code:
import urllib2
if __name__ == '__main__':
url = 'http://hh'
try:
urllib2.urlopen(url, timeout=5)
except URLError, e:
print e.reason
ÎÒ²¶»ñÒì³£ È´ÌáʾÕâÖÖ´íÎó:
except URLError, e:
NameError: name 'URLError' is not defined
ÊÇÔõô»ØÊ Ϊʲô˵ÎÒ䶨ÒåÄØ?
¸ÃÔõô¸Ä²Å¿ÉÒÔÄØ
»¹ÓÐ Âé·³¸æÖªÒ»ÏÂ ÍøÒ³¸÷ÖÖ·µ»Ø´íÎóÔõô²¶»ñÄØ
¿ÉÄÜÊÇûµ¼ÈëºÏÊʵĿâ
²»ÊÇÓиö¸üºÃµÄÀý×Óô
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
response = urlopen(req)
except HTTPError, e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError, e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
# everything is fine
Ïà¹ØÎÊ´ð£º
ʹÓÃÔ´Îļþ
#!/usr/bin/python
# Filename : helloworld.py
print 'Hello World'
ÎÒÔõôҲ¿´²»¶®£¡Ö»ÊÇ×îºóÒ»ÐÐÎÒÖªµÀ~~Ç°ÃæÁ½ÐÐÊÇʲôÒâË¼ÄØ£¿
½Ì³ÌÉÏ˵Èç¹ûÄãʹÓÃIDLE£¬ÇëʹÓò˵ ......
ÎÒÿ´ÎÉÏ´«µÄÎļþ¶Áµ½µÄÊý¾Ý¶¼²»ÕýÈ·¡£2M µÄͼƬ¶ÁµÃ10¶àK ¡£¡£ÄÄλ´óÏÀ¿ÉÒÔ°ï°ïÎÒ°¡¡£
#!D:\ProgrammerTools\python26\python.exe
#encoding=utf-8
import cgitb
import os
cgitb.enable()
import cgi,urllib ......
´ó¼ÒºÃ£¬ÎÒÊÇÒ»¸öÐÂÊÖ£¬¸Õ¿ªÊ¼Ñ§python£¬µ«ÊǸտªÊ¼µÄhelloworld¶¼Ã»·¨´òÓ¡£¬ÈÃÎÒºÜÎÞÄΡ£
ÎÒµÄpython°²×°Â·¾¶Îªf:\python31¡£ÔÚpathÖÐÒ²ÉèÖöÔÁË£¬ÔÚwindowsÏÂÔËÐÐÊÇÕâÑùÏÔʾµÄ£¬Ï£Íû¸÷λǰ±²Ö¸µãһϡ£Ð»Ð»
Pyth ......