Python實現多併發訪問網站功能示例

NO IMAGE
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

本文例項講述了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併發程式設計之多程序、多執行緒、非同步和協程詳解Python控制多程序與多執行緒併發數總結python實現多執行緒的方式及多條命令併發執行python多執行緒threading.Lock鎖用法例項詳解Python中的多執行緒程式設計淺析Python中的多程序與多執行緒的使用基python實現多執行緒網頁爬蟲Python threading多執行緒程式設計例項python實現用於測試網站訪問速率的方法python訪問抓取網頁常用命令總結Python的Django應用程式解決AJAX跨域訪問問題的方法

相關文章

程式語言 最新文章