#-*-coding:utf-8-*-ImportUrllib2#URLLIB2 The default user-agent is python-urllib/2.7#User-agent is the first step in the struggle between reptiles and reptiles.Ua_headers = { "user-agent":"mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/50.0.2661.102 ubrowser/6.1.2716.5 safari/537.36"}#through URLLIB2. Request () Constructs a requesting objectRequest = Urllib2. Request ("http://www.baidu.com/", headers =ua_headers)#sends a request to the specified URL address and returns the class file object for the server responseResponse =Urllib2.urlopen (Request)#the class file object returned by the server supports how Python file objects are manipulated#Read () reads all the contents of the file, returns the stringHTML =Response.read ()#response: Is the server response class file, in addition to supporting file operation methods, but also support the following common methods#return HTTP response code, successful return to 200,4 Server Page error, 5 server issuePrintResponse.getcode ()#returns the actual URL that returns the actual data, preventing redirection issuesPrintResponse.getcode ()#returns the HTTP header of the server responsePrintResponse.info ()PrintHtml
Get Web page source code