python objects in urllib.request Case

Something new to reptiles, from time to time review was based on the job, so full of posts in any case have the cheek to turn ah!

What is Urllib library?

urllib library is a  Python  built-in HTTP request repository. urllib upper interface module provides the data access on the www and ftp like to access a local file.

There are several modules:

1.urllib.request request module

2. urllib.error exception handling module

3. urllib.parse url parsing module

4. urllib.robotparser robots.txt parsing module

Several basic module in Urllib library using the following:

urllib.request

About the urllib.request : the urllib.request module provides basic configuration HTTP (or other protocols such as FTP) request method, it can be simulated by using a browser of a request to initiate the process. Use different protocols to acquire URL information. Some of its interface to be able to handle basic authentication (Basic Authenticaton), the case of redirections (HTTP redirection), Cookies (browser Cookies) and so on. These interfaces are provided by handlers and openers objects.

1. Common methods

  read () == read the file contents
  geturl () == acquisition request URL
  getHeaders () == http request header information acquisition
  getcode () == Get Status Code
  readlines () == acquisition line

2. Case

Coding = UTF- # . 8 
#import the urllib.request 
# ========= Response method 
#read () == read the file contents 
#geturl () == acquisition request URL 
#getheaders () == Get http request header 
#getcode () == Get status code 
#readlines () == acquired line 
#URL = " http://www.baidu.com " ; 
#response = the urllib.request.urlopen (URL); 
# = ==== case. 1 
# STR = response.read () decode ();. # by this is converted to decode UTF8 
# with Open ( " baidu.html " ," W " , encoding = " UTF8 " ) AS FP: 
# fp.write (STR); 
# ================ case 2 flows through the write byte = default is read out by the read byte stream 
# with Open ( " bai.html " , " WB " ) AS FP: 
# fp.write (response.read ()); 
# == byte stream read stored image 
# image_url = ' https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy /it/u=3772530225,1800402028&fm=26&gp=0.jpg ' ; 
# Response = the urllib.request.urlopen (image_url);
# with open("mv.jpg " , ' WB ' ) AS FP: 
# fp.write (response.read ()); 
# 3 Case == using the built-in function to read image 
#image_url = ' https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy /it/u=3772530225,1800402028&fm=26&gp=0.jpg ' ; 
# urllib.request.urlretrieve (image_url, " chun.jpg " );

 

Guess you like

Origin www.cnblogs.com/zh718594493/p/12391296.html