python用法: post一个http请求, schedule一个task

来源:互联网 发布:qq软件升级 编辑:程序博客网 时间:2024/04/27 21:27

内容在http://iihero.cn上也有,这里转摘一下。
近期用空闲时间看了看python的一部分module,感觉这斯功能确实so good, so powerful.
(1) 用它post一个http请求:



import urllib,urllib2,cookielib 
def post3():   
# for mail.sina.com.cn

    cj 
= cookielib.CookieJar() 
    url_login 
= 'http://mail.sina.com.cn/cgi-bin/login.cgi' 
    body 
= (('logintype','login'), ('u','username'), 
        (
'psw''********'))
    opener
=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
    
#opener.addheaders = [('User-agent', 'Opera/9.23')] 
    opener.addheaders = [('User-agent'
        
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]
    urllib2.install_opener(opener) 
    req
=urllib2.Request(url_login,urllib.urlencode(body)) 
    u
=urllib2.urlopen(req)
    
print u.read().decode('utf-8').encode('gbk')

 

下午,试了一下python的http 相关类的方法,用上述代码登录新浪邮箱,试了一段时间,
比较关键的是User-agent,上边两种浏览器的agent都支持。估计python默认的User-agent得不到sina.com的验证。

python写这种http method代码还是蛮方便的。

(2) 写一个定时执行任务的小东东,这里是单线程版本,要改成多线程的也容易。

 

#!/usr/bin/env python
#
coding=utf-8

import thread, time

def task():
    
'''
    Here we can execute some task to be scheduled every n seconds
    
'''
    
print "task doing ... ..."

def main(n):
    t 
= time.time()
    start_t 
= t
    end_t 
= start_t + 60*60*72
    
#while (t < end_t):
    while True:
        task()
        time.sleep(n)
        t 
= time.time()
        
if __name__ == "__main__":
    
    
try:
        main(
5)
    
except KeyboardInterrupt:
        
print "System exit ... ... "
        sys.exit(
1)
<script type="text/javascript"><!--google_ad_client = "ca-pub-7104628658411459";/* wide1 */google_ad_slot = "8564482570";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击