如何使用Python和多进程检查网页是否存活
我有一份大约25000个网址的列表,我想检查这些网址是否可用(也就是返回200的响应)。我想用Python的multiprocessing库来并行检查这些网址。我写了下面的代码(主要参考了Python文档的例子),但是运行起来似乎很慢。有没有什么办法可以让这个脚本运行得更快呢?
import urllib2
import time
import random
from multiprocessing import Process, Queue, current_process, freeze_support
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
#
# Function run by worker processes
#
def worker(input, output):
for args in iter(input.get, 'STOP'):
result = alive(args)
output.put(result)
#
# Functions referenced by tasks
#
def alive(x):
x = x.strip()
try:
return x, ":", urllib2.urlopen(HeadRequest(x)).getcode()
except urllib2.HTTPError as e:
return x, ":", e.code
except:
return x, ": Error"
#
#
#
def check():
NUMBER_OF_PROCESSES = 500
text_file = open("url.txt", "r")
TASKS1 = text_file.readlines()
# Create queues
task_queue = Queue()
done_queue = Queue()
# Submit tasks
for task in TASKS1:
task_queue.put(task)
# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
for i in range(len(TASKS1)):
print done_queue.get()
# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
if __name__ == '__main__':
freeze_support()
check()
任何帮助都非常感谢
1 个回答
1
有一个简单的方法:
Scrapy 是一个为 Python 提供的网络爬虫框架:你可以给它一份需要爬取的网址列表(在你的情况下,它不需要跟随链接),它会自动根据你设定的进程或线程限制,扩展成多个爬虫运行——你不需要自己去了解多进程通信和扩展的细节。
http://doc.scrapy.org/topics/scrapyd.html#topics-scrapyd
你自己需要做的就是分析结果。