通過前面這麼屢次的失敗,咱們也得到了不少知識,獲得了不少經驗,這時候再不上源碼的話就天理不容了html
#!/usr/bin/env python # -*- coding:UTF-8 -*- __author__ = "217小月月坑" ''' 驗證碼登錄OK ''' import urllib import urllib2 import cookielib # 網址 Img_URL = 'https://id.ifeng.com/public/authcode' Login_URL = 'https://id.ifeng.com/api/sitelogin' Blog_URL = 'http://blog.ifeng.com/16441366.html' headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0'} cookieJar = cookielib.CookieJar() handlers = urllib2.HTTPCookieProcessor(cookieJar) opener = urllib2.build_opener(handlers) urllib2.install_opener(opener) # 向驗證碼的網址發送請求 img_req=urllib2.Request(Img_URL,headers=headers) img_response=opener.open(img_req) print cookieJar # 文件操做,下載驗證碼 f = open('/home/ym/code','wb') f.write(img_response.read()) f.flush() f.close() print "驗證碼圖片下載完成" # 提示用戶輸入驗證碼 captcha = raw_input("請輸入驗證碼:") # 構造post數據 data = { 'u': '2027598917@qq.com', 'k': 'hp201112701254', 'auth': captcha, 'auto': 'on', 'comfrom':'', 'type': '2', } post_data = urllib.urlencode(data) # 將post 信息發送到接受信息的網址,登錄 login_req = urllib2.Request(Login_URL,post_data) login_response = opener.open(login_req) print cookieJar blog_response = opener.open(Blog_URL) print cookieJar print blog_response.read()
好了,看看登錄成功以後返回的是什麼python
就是這麼簡單的幾行代碼,OK,這個實例到這裏就結束啦
api