2016年5月14日 星期六

ubuntu 下使用 headless browser PhantomJS

PhantomJS 是一個 無畫面 的 browser
非常適合用來與 selenium 配合進行 自動化測試或是爬蟲程式
例如:

#取得 selenium driver 物件
def getDriver(self):
    driver = None
    if os.name == "nt":
        #chromeDriverExeFilePath = os.sep.join(("bennu_res", "chromedriver.exe"))
        #driver = webdriver.Chrome(chromeDriverExeFilePath)
        phantomjsDriverExeFilePath = os.sep.join(("bennu_res", "phantomjs.exe"))
        driver = webdriver.PhantomJS(phantomjsDriverExeFilePath)
    if os.name == "posix":
        phantomjsDriverExeFilePath = os.sep.join(("bennu_res", "phantomjs"))
        driver = webdriver.PhantomJS(phantomjsDriverExeFilePath)
    return driver

selenium 用法 本篇暫不介紹

PhantomJS 下載之後只有一個執行檔,將他放在 selenium 可以讀取到的位置即可使用
在 ubuntu 環境下,有幾點要注意的是:
1. 必須 chmod 755 phantomjs 加入執行權限
2. 必須安裝 apt-get install fontconfig 套件

沒有留言: