python用法: post一个http请求, schedule一个task
内容在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)
#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)