【问题标题】:How would you make this script run faster?你如何让这个脚本运行得更快?
【发布时间】:2014-02-10 03:45:10
【问题描述】:
import urllib2
import time

def hunt(url, start="<blockquote>", end="</blockquote>"):
    while 1:
        x = urllib2.urlopen(url)
        y = x.read()
        print y[y.find(start):y.find(end)]
        time.sleep(1)

我正在尝试不断更新网页上的单个元素,包括避免被服务器禁止的时间间隔。它不一定是 python,顺便说一句。

【问题讨论】:

  • 如果服务器只允许你每隔一段时间运行一次,它到底需要多快?
  • 我会尝试找出服务器的速率限制,但在客户端我也想更快地进行解析。我的意思是像华尔街一样快。
  • 网站有 API 吗?或许不用拉整个页面也能拿到值。

标签: python web-scraping webpage performance processing-efficiency


【解决方案1】:

我们来做个实验,比较str.find()re.search()的速度:

import timeit

setup = '''
import urllib2
import re
start = "<body>"
end = "</body>"
url = 'http://www.stackoverflow.com'
req = urllib2.urlopen(url)
res = req.read()
regex = re.compile('%s.+?%s' % (start, end))
'''

timeit.timeit('''res[res.find(start):res.find(end)]''',
    setup = setup, number = 1000)

timeit.timeit('''res[res.find(start):res.rfind(end)]''',
    setup = setup, number = 1000)

timeit.timeit('''regex.search(res)''',
    setup = setup, number = 1000)

这样我们得到:

0.16357661195633

0.08454644330907968

0.2768974693601649

所以看起来str.find() 的速度相当不错,但如果你知道你的结束报价会比开始更接近结束,你可以使用str.rfind() 加快速度。

您可以做的另一件事是使用多个线程。启动一个线程,不断获取 URL 并将它们放入队列中,然后让另一个线程处理队列。这样,当第一个线程在等待 IO 时休眠时,第二个线程将处理来自前一个 URL 的字符串。大致是这样的:

import Queue
import threading
import urllib2

q = Queue.Queue()
results = []

url = 'http://www.google.com/'
start = '<body>'
end = '</body>'

def get_urls():
    while 1:
        req = urllib2.urlopen(url)
        res = req.read()
        print "putting data len", len(res)
        q.put(res)

def process_url():
    url_data = q.get()
    result = url_data[url_data.find(start):url_data.find(end)]
    results.append(result)
    q.task_done()

putter_thread = threading.Thread(target = get_urls)
getter_thread = threading.Thread(target = process_url)

putter_thread.start()
getter_thread.start()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多