URLLIB Module of network programming

Source: Internet
Author: User

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

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.