首页 > 后端开发 > php教程 > Python多并发访问网站

Python多并发访问网站

巴扎黑
发布: 2023-03-14 18:46:02
原创
1854 人浏览过

这篇文章主要介绍了Python实现多并发访问网站功能,结合具体实例形式分析了Python线程结合URL模块并发访问网站的相关操作技巧,需要的朋友可以参考下

本文实例讲述了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&#39;%4d %s Spent:%7s seconds&#39;%(i,url,span))
    file.write(u&#39;%4d %s ST:%s ET:%s Spent :%s seconds\n&#39;%(i,url,startTime,endTime,span))
  file.write(&#39;\n&#39;)
  print(u&#39;\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&#39;%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s))
  file.write(u&#39; 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&#39;%(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(&#39;threads_data.txt&#39;,&#39;a&#39;) # save threads_data
    file.write( "%s says Hello World at time: %s\n" % (self.getName(), now))
    Process(&#39;http://222.20.6.184/main.aspx&#39;,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__==&#39;__main__&#39;:
#  file = open(&#39;threads_data.txt&#39;,&#39;w&#39;)
#  file.close()
#  file = open(&#39;data.txt&#39;,&#39;w&#39;)
#  file.close()
  for i in range(1000): # 多少次同时并发访问
    t = ThreadClass()
    t.start()
登录后复制

以上是Python多并发访问网站的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板