天天看點

Python之URLLIB

#!/usr/bin/env python

#coding:utf8

import urllib

def print_list(list):

    for i in list:

        print i

def demo():

    s=urllib.urlopen("http://dbspace.blog.51cto.com")#打開URL

    lines=s.readlines()

    print s.read(100)#讀出所有的資料

    print s.readlines#讀出所有以清單方式顯示出來

    print s.readline#隻讀出一行的資料,若要更多可以用for循環

    print_list(lines)#逐行列印出來,配上print_list

    print s.getcode()#列印應答碼,可以傳回的為200,不存在的為404

    ###

    info():傳回http頭部的資訊

    msg=s.info()

    print msg.headers#http頭的内容

    print msg.items()#解析過的頭的清單

###通過dir(msg)方法可以看到更多的方法

##把遠端的檔案下載下傳到本地(遠端位址,儲存檔案名,下載下傳進度)

def retrieve():

    urllib.urlretrieve("http://dbspace.blog.51cto.com","index.html",reporthook=process)

def process(blk,blk_size,total_size):#監控目前下載下傳狀态進度資訊reporthook(目前傳輸的塊數,塊大小,資料總大小)

def process(blk,blk_size,total_size):

    print '%d/%d - %.02f%'%(blk*blk_size,total_size,float(blk*blk_size)*100/total_size)

更多參數:

urllib.urlencode(參數)#加密

import urlparse

urlparse.parse_qs(參數)#解密

if __name__=="__main__":

    demo()

    retrieve()

def download(stock_list):

    for sid in stock_list:

        url='http://table.finace.yahoo.com/table.csv?s='+sid

        fname=sid+'.csv'

        urllib.urlretrieve(url,fname)##這樣就是下載下傳所有資料

def download_data_in_period(stock_list,start,end):

        params={'a':start.month-1,'b':start.day,'c':start.year,'d':end.month-1,'e':end.day,'f':end.year,'s':sid}

        qs=urllib.urlencode(params)

        url=url+qs

        fname='%s_%d%d%d_%d%d%d.csv'%(sid,start.year,.....)

        urllib.urlretrieve(url,fname)

if __name__=="__name__":

    stock_list=['222.sz','3333.sz']

    download(stock_list)