1.一般請求:
<pre name="code" class="python">req = urllib2.Request("http://www.baidu.com")fd = urllib2.urlopen(req)while 1:data = fd.read(1024)if not len(data):breakprint data
2. 認證 (TBD)
3. 表單:
GET:1) 與一般請求相似,手工把GET參數添加到URL中,<span style="font-family: Arial, Helvetica, sans-serif;">手工構造URL時空格應該換成“+”。 構造的過程可能非常的複雜。
req = urllib2.Request("http://www.freebsd.org/cgi/search.cgi?words=python+socket&max=25&source=www")fd = urllib2.urlopen(req) 2) 使用urllib.urlencode()方法
def addGETdata(url, data):return url + '?' + urllib.urlencode(data) def get_method_in_form2():#paramzipcode = [("words", "python socket"), ("max", "25") ,("source", "www")]url = addGETdata('http://www.freebsd.org/cgi/search.cgi', zipcode)req = urllib2.Request(url)fd = urllib2.urlopen(req)
POST:一樣是使用urllib.urlencode()方法對參數編碼,urllib2.urlopen()方法發送請求,只是參數不是放在URL中, 而是做為urlopen的第二個參數
zipcode = [("query", "10001")]data = urllib.urlencode(zipcode)url = 'http://www.wunderground.com/cgi-bin/findweather/getForecast'req = urllib2.Request(url)fd = urllib2.urlopen(req, data)
4 錯誤處理 (TBD)