gpt4 book ai didi

python - 抓取 160.000 页 - 太慢了

转载 作者:太空狗 更新时间:2023-10-30 01:23:04 25 4
gpt4 key购买 nike

我有一个包含超过 160.000 个 url 的文件,我想从其中的页面中抓取一些信息。该脚本大致如下所示:

htmlfile = urllib2.urlopen(line)
htmltext = htmlfile.read()
regexName = '"></a>(.+?)</dd><dt>'
patternName = re.compile(regexName)
name = re.findall(patternName,htmltext)
if name:
text = name[0]
else:
text = 'unknown'

nf.write(text)

哪个有效,但是非常非常慢。刮掉所有 160.000 页需要四天多的时间。有什么加快速度的建议吗?

最佳答案

对您的代码的一些建议:

当你编译正则表达式模式时,确保你也使用了编译后的对象。并避免在每个处理循环中编译您的正则表达式。

pattern = re.compile('"></a>(.+?)</dd><dt>')
# ...
links = pattern.findall(html)

如果您想避免使用其他框架,那么最好的解决方案是加快速度,因此请使用标准线程库,以便并行进行多个 HTTP 连接 .

像这样:

from Queue import Queue
from threading import Thread

import urllib2
import re

# Work queue where you push the URLs onto - size 100
url_queue = Queue(10)
pattern = re.compile('"></a>(.+?)</dd><dt>')

def worker():
'''Gets the next url from the queue and processes it'''
while True:
url = url_queue.get()
print url
html = urllib2.urlopen(url).read()
print html[:10]
links = pattern.findall(html)
if len(links) > 0:
print links
url_queue.task_done()

# Start a pool of 20 workers
for i in xrange(20):
t = Thread(target=worker)
t.daemon = True
t.start()

# Change this to read your links and queue them for processing
for url in xrange(100):
url_queue.put("http://www.ravn.co.uk")

# Block until everything is finished.
url_queue.join()

关于python - 抓取 160.000 页 - 太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17137249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com