所以我一直在研究10k +页面上的刮刀并从中抓取数据。
问题是随着时间的推移,内存消耗急剧增加。因此,为了克服这一点而不是仅在scrape scraper结束时关闭驱动程序实例,因此它会在每个页面加载并提取数据后关闭实例。
但由于某种原因,ram记忆仍然存在。
我尝试使用PhantomJS但由于某种原因它没有正确加载数据。我还尝试使用初始版本的scraper将Firefox中的缓存限制为100mb,这也不起作用。
注意:我使用chromedriver和firefox实例运行测试,不幸的是我不能使用诸如请求,机械化等库来代替selenium。
任何帮助都表示赞赏,因为我一直试图解决这个问题一周。谢谢。
你想说你的司机正在填补你的记忆吗?你是怎么关闭他们的?如果你要提取数据,你是否仍然引用了一些将它们存储在内存中的集合?
你提到当你在抓取结束时关闭驱动程序实例时你已经没有内存了,这使你看起来像是在保留额外的引用。
强制Python解释器释放内存到操作系统的The only way是终止进程。因此,使用multiprocessing
生成selenium Firefox实例;生成的进程终止时将释放内存:
import multiprocessing as mp
import selenium.webdriver as webdriver
def worker()
driver = webdriver.Firefox()
# do memory-intensive work
# closing and quitting is not what ultimately frees the memory, but it
# is good to close the WebDriver session gracefully anyway.
driver.close()
driver.quit()
if __name__ == '__main__':
p = mp.Process(target=worker)
# run `worker` in a subprocess
p.start()
# make the main process wait for `worker` to end
p.join()
# all memory used by the subprocess will be freed to the OS
另见Why doesn't Python release the memory when I delete a large object?
我遇到了类似的问题并且破坏了我自己的驱动程序(即将驱动程序设置为None)可以防止那些内存泄漏
在将webdriver.get(url)
语句放在try / except / finally语句中之前我遇到了同样的问题,并确保webdriver.quit()
在finally语句中,这样,它总是执行。喜欢:
webdriver = webdriver.Firefox()
try:
webdriver.get(url)
source_body = webdriver.page_source
except Exception as e:
print(e)
finally:
webdriver.quit()
来自docs:
这种语句的finally子句可用于指定不处理异常的清理代码,但是在前面的代码中是否发生异常时执行。