Simulating HTTP requests is a common requirement, in Python, with HTTP module operations.
1 Importhttp.client2 3 #Create an Http connection. 4HTTP = http.client.HTTPConnection ('www.baidu.com')5 #set the request, the first parameter is the request method, and the second parameter is the requested page. 6Http.request ('GET','/')7 #get the content of Baidu homepage, return is a bytes. 8HTML =http.getresponse (). Read ()9 #close the Http connection. Ten http.close () One A #Create a new file and use Utf-8 encoding, otherwise the write error occurs. -File = Open (r'e:\temp\baidu.html','W', encoding='Utf-8') - #writes the decoded Html content. the File.write (Html.decode ()) - #close the file. -File.close ()
It is worth noting that we need to set up the code, in Python, the open new file is ASCII by default, and we get the content is Unicode, so the direct write error. Output in command-line mode is the same, because the command line encoding mode is GBK.
Python Learning -19.python HTTP Module