Urllib Implementation---Timeout, get HTTP response code, redirect, proxy settings

Source: Internet
Author: User
Tags response code

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.