欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python实现多并发访问网站功能示例

时间:2020-12-23 12:04:57|栏目:Python代码|点击:

本文实例讲述了Python实现多并发访问网站功能。分享给大家供大家参考,具体如下:

# Filename:visitweb_threads.py
# Description:python visit web, get startTime, endTime, everytimes spentTime,threading
import threading
import urllib
import time
import datetime
print 'num    web       SpentTime'
def Process(url,n):
  minSpan = 0.0
  maxSpan = 0.0
  sumSpan= 0.0
  over1s = 0
  file = open('data.txt','a') # save Data
  for i in range(n):
    startTime =datetime.datetime.now()
    try:
      urlItem = urllib.urlopen(url)
      htmSource = urlItem.read()
      urlItem.close()
    except:
      pass
    endTime = datetime.datetime.now()
    span = (endTime-startTime).total_seconds()
    sumSpan = sumSpan + span
    if span < minSpan:
      minSpan = span
    if span > maxSpan:
      maxSpan = span
    if span>1:
      over1s=over1s + 1
    print(u'%4d %s Spent:%7s seconds'%(i,url,span))
    file.write(u'%4d %s ST:%s ET:%s Spent :%s seconds\n'%(i,url,startTime,endTime,span))
  file.write('\n')
  print(u'\n requested:%s times\n Total Spent:%s seconds\n avg:%s seconds\n max:%s seconds\n min:%s seconds\n over 1 secnod:%s times\n'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s))
  file.write(u' requested:%s times\n Total Spent:%s seconds\n avg:%s seconds\n max:%s seconds\n min:%s seconds\n over 1 secnod:%s times\n'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s))
  file.close()
class ThreadClass(threading.Thread):
  def run(self):
    now = datetime.datetime.now()
    print "%s says Hello World at time: %s" % (self.getName(), now)
    file = open('threads_data.txt','a') # save threads_data
    file.write( "%s says Hello World at time: %s\n" % (self.getName(), now))
    Process('http://222.20.6.184/main.aspx',10) # visit website 网站的Url和每个进程的访问次数
    now = datetime.datetime.now()
    print "%s says Goodbye at time: %s" % (self.getName(), now)
    file.write( "%s says Goodbye at time: %s\n" % (self.getName(), now))
    file.close()
if __name__=='__main__':
#  file = open('threads_data.txt','w')
#  file.close()
#  file = open('data.txt','w')
#  file.close()
  for i in range(1000): # 多少次同时并发访问
    t = ThreadClass()
    t.start()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

上一篇:Python os.access()用法实例

栏    目:Python代码

下一篇:PyCharm代码提示忽略大小写设置方法

本文标题:Python实现多并发访问网站功能示例

本文地址:http://www.codeinn.net/misctech/35740.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有