因為最近剛好有機會寫到相關的東西, 所以順便記錄一下

Requests

首先你需要安裝這個library. 一個挺好用的http libaray

官方網站: http://docs.python-requests.org/en/master/

Login

根據以下的code就能順利進入了. 印出來的東西應該是login後轉跳的webpage的內容.

# -*- coding: utf-8 -*-

import requests
import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')

HOST = 'YOUR_HOST'

# Start a session so we can have persistant cookies
session = requests.session()

# This is the form data that the page sends when logging in
login_data = {
    'id': 'YOUR_ID',
    'password': 'YOUR_PW',
}

# Authenticate
r = session.post(HOST + "/your/path", data=login_data)
print r.content

Other API

那如果你是想要login後接著呼叫其他API的話. 首先你必須要記錄cookie, 接著在每次呼叫API時把cookie帶入. 如以下範例:

# -*- coding: utf-8 -*-

import requests
import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')

HOST = 'YOUR_HOST'

# Start a session so we can have persistant cookies
session = requests.session()

# This is the form data that the page sends when logging in
login_data = {
    'id': 'YOUR_ID',
    'password': 'YOUR_PW',
}

# Authenticate
r = session.post(HOST + "/your/path", data=login_data)
cookies = session.cookies

def main():
	payload = {
		'page': 1,
		'keyword': '',
	}

	url = HOST + "/your/path"
	print url
	r = requests.post(url, data=payload, cookies=cookies)
	print r.content

if __name__ == "__main__":
    main()