python urllib的基本使用方法

#_*_ coding:utf-8 _*_
#Author:gaoqiang
import urllib
import urllib2


#基本使用
def demo_base(url="http://www.baidu.com/"):
    try:
        req=urllib2.urlopen(url,timeout=3)
    except urllib2.HTTPError,e:
        print e
    else:
        print req.read()


#添加http头
def demo_add_httpheader(url="http://blog.csdn.net/gaomin8"):
    headers={'User-Agent':'Mozilla/5.0','x-my-hester':'my value'}
    req=urllib2.Request(url,headers=headers)
    s=urllib2.urlopen(req)
    html=s.read()
#    print html
    s.close()
    save_file("test.html",txt=html)


#创建一个打开器
#urllib2.urlopen类似1个最普通的打开器
def demo_create_opener(url="http://blog.csdn.net/gaomin8"):
    headers={'User-Agent':'Mozilla/5.0','x-my-hester':'my value'}
    data={'username':'gaopinqiang@163.com','password':'gaopinqiang8*'}
    data=urllib.urlencode(data)#使用urllib编码
    req=urllib2.Request(url,data=data,headers=headers)
    
    opener=urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
    s=opener.open(req)
    
    html= s.read()
    s.close()
    save_file("test.html",txt=html)
    
    
#使用cookie模块
def demo_cookie(url="http://www.douban.com/"):
    import cookielib
    cookiejar=cookielib.CookieJar()
    handler=urllib2.HTTPCookieProcessor(cookiejar=cookiejar)
    opener = urllib2.build_opener(handler,urllib2.HTTPHandler(debuglevel=1))
    s = opener.open(url)
#    print s.read(100)
    s.close()
    
    print cookiejar._cookies
    
    #发送第二次请求时,自动带上cookie
    s1=opener.open(url)
    print s1.read(100)
    s1.close()
    
#保存文件
def save_file(filepath,txt=""):
    files=open(filepath,"wb")
#    files.write(txt)
    for line in txt:
        files.write(line)
    
    
if __name__=="__main__":
#    demo()
#    demo_add_httpheader()
#    demo_create_opener()
    demo_cookie()
    print "finished"
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值