扫描网站内容(快速) [英] scan websites for content (fast)
本文介绍了扫描网站内容(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个数据库中有数千个网站,我想在所有网站中搜索特定的字符串。做这件事最快的方法是什么?我认为我应该先获取每个网站的内容--这就是我的做法:
import urllib2, re
string = "search string"
source = urllib2.urlopen("http://website1.com").read()
if re.search(word,source):
print "My search string: "+string
并搜索该字符串。但这是非常缓慢的。我如何在Python中加速它?
HTTPS
我认为您的问题不在于程序,而在于您正在为数以千计的站点执行推荐答案请求。您可以研究涉及某种并行处理的不同解决方案,但无论您使解析代码的效率有多高,您都会在当前实现中遇到请求的瓶颈。
这里有一个使用Queue
和threading
模块的基本示例。我建议阅读多处理与多线程相比的好处(如@JonathanV提到的帖子),但这有望对理解正在发生的事情有所帮助:
import Queue
import threading
import time
import urllib2
my_sites = [
'http://news.ycombinator.com',
'http://news.google.com',
'http://news.yahoo.com',
'http://www.cnn.com'
]
# Create a queue for our processing
queue = Queue.Queue()
class MyThread(threading.Thread):
"""Create a thread to make the url call."""
def __init__(self, queue):
super(MyThread, self).__init__()
self.queue = queue
def run(self):
while True:
# Grab a url from our queue and make the call.
my_site = self.queue.get()
url = urllib2.urlopen(my_site)
# Grab a little data to make sure it is working
print url.read(1024)
# Send the signal to indicate the task has completed
self.queue.task_done()
def main():
# This will create a 'pool' of threads to use in our calls
for _ in range(4):
t = MyThread(queue)
# A daemon thread runs but does not block our main function from exiting
t.setDaemon(True)
# Start the thread
t.start()
# Now go through our site list and add each url to the queue
for site in my_sites:
queue.put(site)
# join() ensures that we wait until our queue is empty before exiting
queue.join()
if __name__ == '__main__':
start = time.time()
main()
print 'Total Time: {0}'.format(time.time() - start)
有关threading
的好资源,请参阅Doug Hellmann的帖子here、IBM文章here(如上所述,这已成为我的通用线程设置)和实际文档here。
这篇关于扫描网站内容(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文