python写的多线程访问网页工具

很简单的多线程访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import urllib
import socket
from threading import *

url = "http://www.baidu.com/s?ie=UTF-8&wd=ypw"
cishu = 0
socket.setdefaulttimeout(15)

def gethtml():
global cishu
cishu += 1
print cishu
urllib.urlopen(url).read()

def attack():
while True:
try:
gethtml()
except error:
pass

def run():
t = Thread(target=attack)
t.start()

for i in range(10):
run()

值得注意的地方有:全局变量要用global,需要用try和timeout来防止线程崩溃