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):

    for sid in stock_list:

        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)

    end=datetime.date(year=2016,month=12,day=1)

    start=datetime.date(year=2016,month=11,day=1)

    download_data_in_period(stock_list,start,end)


本文转自 DBAspace 51CTO博客,原文链接:http://blog.51cto.com/dbaspace/1878690


相关文章
|
4月前
|
Python
Python Requests 基本使用(与 urllib 的区别)
Python Requests 基本使用(与 urllib 的区别)
51 0
|
2月前
|
数据采集 应用服务中间件 数据安全/隐私保护
Python爬虫urllib详解#3
摘要:urllib深度解析与高级用法、robots协议分析【2月更文挑战第9天】
51 1
Python爬虫urllib详解#3
|
8月前
|
搜索推荐 Python
Python 基于 urllib 使用 Handler 处理器(代理)
Python 基于 urllib 使用 Handler 处理器(代理)
52 0
|
7月前
|
JSON 监控 Linux
|
7月前
|
Ubuntu Shell Python
|
7月前
|
数据采集 搜索推荐 Python
|
7月前
|
Python
|
7月前
|
Python
|
7月前
|
Web App开发 Linux PHP
|
7月前
|
Web App开发 Linux iOS开发

热门文章

最新文章