#encoding: Utf-8import urllibimport urllib2import cookielibfrom bs4 Import beautifulsoupfilename = ' Cookie_csdn.txt ' # Declares a Mozillacookiejar object instance to hold the cookie, and then writes the file cookie = cookielib. Mozillacookiejar (filename) #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器handler = urllib2. Httpcookieprocessor (cookie) #通过handler来构建openeropener = Urllib2.build_opener (handler) loginurl = "https:// Passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn "#登陆前准备: Get lt and exectionresponse = Opener.open ( loginurl) soup = BeautifulSoup (Response.read ()) for input in Soup.form.find_all ("input"): If Input.get ("name") = = "LT": lt = Input.get ("value") if Input.get ("name") = = "Execution": execution = Input.get ("value") #post信息postdat A = {"username": "[email protected]", "Password": "xxxxxx", "LT": lt, "execution": execution , "_eventid": "Submit"}postdata = Urllib.urlencode (postdata) opener.addheaders = [("User-agent", "mozilla/5.0" (Win dows NT 10.0; Win64; x64) APPLEWEBKit/537.36 (khtml, like Gecko) chrome/51.0.2704.63 safari/537.36 ")] #模拟登录, save the cookie to cookie.txt in result = Opener.open ( Loginurl, PostData) #保存cookiecookie. Save (Ignore_discard=true, ignore_expires=true) #登陆后我们随意跳转到博客获取内容url = "http:// Blog.csdn.net "response = Opener.open (URL) #读取内容保存到html文件中 for easy viewing f = open (' csdn_index.html ', ' W ') F.write (Response.read ( )); F.close () print ' OK '
Python Emulation login CSDN code