我的数据库中有数千个网站,我想在所有网站中搜索特定字符串。最快的方法是什么?我认为我应该首先获取每个网站的内容 - 这就是我这样做的方式:
import urllib2, re
string = "search string"
source = urllib2.urlopen("http://website1.com").read()
if re.search(word,source):
print "My search string: "+string
并搜索该字符串。但这非常慢。我怎样才能在Python中加速它?
我不认为你的问题是程序 - 事实上你正在对数千个站点执行 HTTP 请求。您可以研究涉及某种并行处理的不同解决方案,但无论解析代码的效率如何,您都将遇到当前实现中的请求瓶颈。
这是一个使用的基本示例Queue
and 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 http://www.doughellmann.com/PyMOTW/threading/,一篇 IBM 文章here http://www.ibm.com/developerworks/aix/library/au-threadingpython/(这已经成为我的一般线程设置,如上面所证明的)和实际的文档here http://docs.python.org/2/library/threading.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)