`
iihero
  • 浏览: 264439 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多

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



importurllib,urllib2,cookielib
defpost3():
#formail.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;MSIE6.0;WindowsNT5.1)')]
urllib2.install_opener(opener)
req
=urllib2.Request(url_login,urllib.urlencode(body))
u
=urllib2.urlopen(req)
printu.read().decode('utf-8').encode('gbk')

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

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

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

#!/usr/bin/envpython
#
coding=utf-8

importthread,time

deftask():
'''
Herewecanexecutesometasktobescheduledeverynseconds
'''
print"taskdoing......"

defmain(n):
t
=time.time()
start_t
=t
end_t
=start_t+60*60*72
#while(t<end_t):
whileTrue:
task()
time.sleep(n)
t
=time.time()

if__name__=="__main__":

try:
main(
5)
exceptKeyboardInterrupt:
print"Systemexit......"
sys.exit(
1)
分享到:
评论

相关推荐

    Python安装包version 3.1.5

    This is Python version 3.1.5 ============================ Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Python Software Foundation. All rights reserved. Python...

    定时发短信

    这涉及到网络请求和JSON数据处理,开发者需要熟悉HTTP协议,了解`GET`和`POST`请求,以及如何使用JSON格式进行数据交换。在Java中,可能使用`HttpURLConnection`或`OkHttp`,Python中可以使用`requests`库。 4. **...

    Foundations for Analytics with Python O-Reilly-2016-Clinton W. Brownley

    Foundations for Analytics with Python by Clinton W. Brownley Copyright © 2016 Clinton Brownley. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 ...

    healthcheckd

    "healthcheckd" 是一个基于Python的健康检查工具,它主要用于监控系统或应用程序的状态,确保它们能够正常运行。这个工具可能包含了各种功能,比如检查网络连接、服务响应、磁盘空间、内存使用情况等,以确保系统的...

    Django+Celery实现动态配置定时任务的方法示例

    Django是一个流行的Python web框架,而Celery则是一个分布式任务队列,适用于处理异步任务和定时任务。结合两者,我们可以创建一个强大的后台任务管理系统。 首先,确保已经正确安装了以下依赖: 1. `celery ...

Global site tag (gtag.js) - Google Analytics