Receive our weekly advanced programming tips for FREE
27.May
Http client in python with urllib
0
| 0 votes
Autor: bookkeeper
Chapter: Python

Python has already the batteries included

Get method

import urllib

params = urllib.urlencode({'param1': 1, 'param2': 2, 'bacon3': 3})

f = urllib.urlopen("http://www.programmersbok.com/?%s" % params)
print f.read()

POST method

import urllib

params = urllib.urlencode({'param1': 1, 'param2': 2, 'bacon3': 3})

f = urllib.urlopen("http://www.programmersbok.com/", params)
print f.read()

Use a own user agent

import urllib

class AppURLopener(urllib.FancyURLopener):
version = "MyUserAgent"

urllib._urlopener = AppURLopener()

Use a proxy

import urllib
proxies = {'http': 'http://proxy.server.com:8080/'}
opener = urllib.FancyURLopener(proxies)
f = opener.open("http://www.programmersbook.com")
f.read()