Bag of ML Words

ML = Machine Learning, Music Love, and Miscellaneous things in daily Livings

Python: urllibはやっぱりなし。requestsを使いましょう

昨日のエントリに対して  n4_tさんが

"requestsがいいですよ"

とさっそくコメントくださったので試してみました。

 

もっと簡単でした。

Requests: HTTP for Humans — Requests 2.4.1 documentation

 

urllibだとこうすれば良い

import urllib

import urllib2

 

#

# Proxy setting

#

proxy = {'http':"http://your.proxy.address:your_port_number/"}

proxy_handler = urllib2.ProxyHandler(proxy)

opener = urllib2.build_opener(proxy_handler)

urllib2.install_opener(opener)

 

#

# URL and the data to send

#

url = "http://www.some.nice.application/hogehoge"

data = {"attribute1" : "inu", "attribute2" : "nuko", "attribute3:"kiji"}

 

#

# Send request

#

POST_data = urllib.urlencode(data) # encodes the dictionary into POST format data. possibly

req = urllib2.Request(url, POST_data) #

responses = urllib2.urlopen(req)

 

#

# Retrieve the whole content

#

the_page = responses.read()

responces.close()

 

#

# Do your fancy computations with the content!!

#


 

 

requestsだとこうすれば良い

import requests

 

# Proxy setting

proxy = {'http':"http://your.proxy.address:your_port_number/"}


# URL and the data to send

url = "http://www.some.nice.application/hogehoge"

data = {"attribute1" : "inu", "attribute2" : "nuko", "attribute3:"kiji"}

 

#

# Send request

#

r = requests.get(url, params=data, proxies=proxy)

 

#

# r has everything.

#

print r.text

print r.encoding

print r.url

 

#

# Do your fancy computations with the content!!

#


 

ほえー簡単簡単。