内容在http://iihero.cn上也有,这里转摘一下。
近期用空闲时间看了看python的一部分module,感觉这斯功能确实so good, so powerful.
(1) 用它post一个http请求:
import urllib,urllib2,cookielib
def post3():
# 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)
print u.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
import thread,time
def task():
'''
Herewecanexecutesometasktobescheduledeverynseconds
'''
print " taskdoing...... "
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 " Systemexit...... "
sys.exit( 1 )
# coding=utf-8
import thread,time
def task():
'''
Herewecanexecutesometasktobescheduledeverynseconds
'''
print " taskdoing...... "
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 " Systemexit...... "
sys.exit( 1 )
本文介绍了使用Python发送HTTP请求及设置定时任务的方法。通过具体的代码示例展示了如何利用Python的urllib2库进行新浪邮箱登录操作,并实现了一个简单的定时执行任务的功能。

被折叠的 条评论
为什么被折叠?



