我已经注意到,如果我尝试实例化单个webdriver.PhantomJS对象并使用它执行整个作业(可以说是“重用”它),我的脚本很快就会变得不稳定,出现零星的内存和连接问题。我的下一次尝试是尝试为每个呈现调用实例化一个新的驱动程序(并在它完成时调用quit() ),这对于超过几个请求也不起作用。我的最后一次尝试是使用subprocess将呈现调用隔离在它自己的进程空间中。但是,即使使用这种到目前为止最稳定的技术,我仍然需要将整个脚本包装在supervisor中,以处理偶尔出现的问题。我知道PhantomJS (和其他自动化浏览器)本身并不是为了抓取(更多是为了测试),但有没有办法让它工作得更稳定呢?
发布于 2016-03-01 12:26:26
我在普通浏览器中使用Selenium和pyvirtualdisplay的方式类似:Python - Headless Selenium WebDriver Tests using PyVirtualDisplay (尽管我使用的是Chrome;只是驱动程序不同而已)。
比我在node和Python中使用PhantomJS的体验要稳定得多。您可能仍然希望使用进程管理器,以防万一,但这种方式对我来说不太容易出错。
此外,我建议编写一个小的Python包装器类,这样您就可以使用with块,并确保您的环境始终得到清理;如果您没有适当地终止会话,您可能最终会导致孤立的浏览器占用内存。
来自我的项目:
import os, time
from selenium import webdriver
from pyvirtualdisplay import Display
class ChromeSession(object):
def __enter__(self):
self.display = Display(visible=0, size=(1024, 768))
self.display.start()
chromedriver = "/usr/lib/chromium/chromedriver"
os.environ["websession.chrome.driver"] = chromedriver
self.driver = webdriver.Chrome(chromedriver)
# Tell the driver to wait (if necessary) in case UI rendering takes a while...
self.driver.implicitly_wait(5)
return self.driver
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
print exc_type, exc_val
print exc_tb
self.driver.quit()
self.display.stop()https://stackoverflow.com/questions/35713650
复制相似问题