1.Timeout Setting timeout
Can only modify socket settings global Timeout
#!/usr/bin/env Python3ImportSocketImporturllib.request#Timeout in secondsTimeout= 2socket.setdefaulttimeout (Timeout)#This call to Urllib.request.urlopen now uses the default timeout#We have a set in the socket modulereq= Urllib.request.Request ('http://www.python.org/') A=Urllib.request.urlopen (req). Read ()Print(a)
2. Get the HTTP response code
# !/usr/bin/env Python3 Import = urllib.request.Request ('http://python.org/')try: Urllib.request.urlopen (req) except Urllib.error.HTTPError as E: Print (E.code) Print (E.read (). Decode ("UTF8"))
3. Exception Handling 1
1 #! /usr/bin/env Python3 2 3 from urllib.request import request, Urlopen 4 5 from urllib.error import Urlerror, Httper Ror 6 7 req = Request (' http://www.python.org/') 8
4. Exception Handling 2
1 #! /usr/bin/env Python3 2 3 from urllib.request import request, Urlopen 4 5 from urllib.error import urlerror 6
7 req = Request ("http://www.python.org/") 8 9 Try:10 response = Urlopen (req) except Urlerror as E:14 15 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 requ Est. ') print (' Error code: ', E.code) ' Else: print ("good!") Print (Response.read (). Decode ("UTF8"))
5. Redirection
Import Urllib.request
Import socket
url = ' https://www.baidu.com '
Response =urllib.request.urlopen (URL)
isrediercted = Response.geturl () = = "Https://www.baidu.com"
6. Proxy settings
Import Urllib.request
Proxy_support = Urllib.request.ProxyHandler ({' Sock5 ': ' localhost:1080 '})
Opener = Urllib.request.build_opener (Proxy_support)
Urllib.request.install_opener (opener)
A = Urllib.request.urlopen ("http://www.python.org/"). Read (). Decode ("UTF8")
Print (a)
Urllib Implementation---Timeout, get HTTP response code, redirect, proxy settings