4

我在数据库中有数千个网站,我想在所有网站中搜索特定字符串。最快的方法是什么?我认为我应该首先获取每个网站的内容 - 这就是我这样做的方式:

import urllib2, re
string = "search string"
source = urllib2.urlopen("http://website1.com").read()
if re.search(word,source):
    print "My search string: "+string

并搜索字符串。但这非常慢。如何在 python 中加速它?

4

2 回答 2

3

我不认为你的问题是程序 - 这是你正在为数千个站点执行 HTTP 请求的事实。您可以研究涉及某种并行处理的不同解决方案,但无论您使解析代码的效率如何,您都将在当前实现中遇到请求的瓶颈。

这是一个使用Queuethreading模块的基本示例。我建议阅读多处理与多线程的好处(例如@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 的帖子,此处是 IBM 文章(已成为我的一般线程设置,如上所示)和实际文档此处

于 2012-11-12T21:31:55.947 回答
2

尝试研究使用多处理同时运行多个搜索。多线程也可以工作,但如果管理不当,共享内存可能会变成一个诅咒。查看此讨论以帮助您了解哪种选择适合您。

于 2012-11-12T22:03:55.827 回答