First of all, Urlib is not a very useful method, here is only a brief introduction. Generally we use the requests method instead of the Urlib method.
1. Get request
1 fromUrllibImportRequest2URL ='http://www.baidu.com'3req = Request.urlopen (URL)#open a URL to send a GET request4Content = Req.read (). Decode ()#读取Source Code5FW = Open ('baidu.html','W', encoding='Utf-8')6Fw.write (content)
Line 1th: Importing the request function from Urllib can also be written as: Import Urllib.request
Line 2nd: The URL link of the GET request, if it is in the interface test, the following parameters should be taken, for example: Http://api.xxxx.cn/api/user/stu_info?stu_name=xiaohei
Line 3rd: Open the URL, send a GET request, get to the
Line 4th: Read the source code, directly read the binary format, to be decoded
Line 5th: Create a file in "W" mode
Line 6th: Write the read source to baidu.html
2. Post request
1 fromUrllibImportRequest,parse2URL ='Http://api.xxxx.cn/api/login'3data = {4 'username':'xxxx',5 'passwd':'xxxxxxxx'6}#Request Data7data = Parse.urlencode (data)#Turn the dictionary into a string: Username=xxxx&passwd=xxxxxxx, spell the parameters8req = Request.urlopen (Url,data.encode ())#incoming parameter to byte type9 Print(Req.read (). Decode ())
Line 1th: Import request from Urllib, parse function
Line 2nd: Request address
Line 3rd: Post entry, defined data is dictionary format
Line 7th: The Parse.urlencode () method turns the dictionary into a string and is stitched into a username=xxxxx&passwd=xxxxxx format.
Line 8th: Incoming arguments to be converted to binary format
Line 9th: Print out the post results to decode.
URLLIB Module of network programming