Python模擬登錄csdn代碼
阿新 • • 發佈:2017-10-18
code http pro submit sub com headers soup eve
#encoding:utf-8 import urllib import urllib2 import cookielib from bs4 import BeautifulSoup filename = ‘cookie_csdn.txt‘ #聲明一個MozillaCookieJar對象實例來保存cookie,之後寫入文件 cookie = cookielib.MozillaCookieJar(filename) #利用urllib2庫的HTTPCookieProcessor對象來創建cookie處理器 handler = urllib2.HTTPCookieProcessor(cookie) #通過handler來構建opener opener = urllib2.build_opener(handler) loginUrl = "https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" #登陸前準備:獲取lt和exection response = 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信息 postdata = { "username":"[email protected]", "password":"xxxxxx", "lt":lt, "execution":execution, "_eventId":"submit" } postdata = urllib.urlencode(postdata) opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36")] #模擬登錄,保存cookie到cookie.txt中 result = opener.open(loginUrl, postdata) #保存cookie cookie.save(ignore_discard=True, ignore_expires=True) #登陸後我們隨意跳轉到博客獲取內容 url = "http://blog.csdn.net" response = opener.open(url) #讀取內容保存到html文件中,方便查看 f = open(‘csdn_index.html‘, ‘w‘) f.write(response.read()); f.close() print ‘ok‘
Python模擬登錄csdn代碼