爬虫類嫌いのPython日記

爬虫類が大の苦手の筆者が、Pythonに挑戦。他にも、RubyやObjective-C、Google Appengine、Herokuなど色々とチャレンジしています。

PythonでGET/POST送信

PythonでGETやPOST送信してみました。
POST送信

import urllib
import urllib2

url    = 'http://example.com/'
params = {'hoge' : 'hogehoge', 'fuga' : 'fugafuga'}
params = urllib.urlencode(params)

req = urllib2.Request(url)
# ヘッダ追加
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
# パラメータ追加 
req.add_data(params)

res = urllib2.urlopen(req)

# レスポンス取得
body = res.read()

GET送信

import urllib
import urllib2

url    = 'http://example.com/'
params = {'hoge' : 'hogehoge', 'fuga' : 'fugafuga'}
params = urllib.urlencode(params)

req = urllib2.urlopen(url + '?' + params)

# レスポンス取得
body = req.read()