解決:Ubuntu(MacOS)+phantomjs+python的部署問題

雲服務器:ESC Ubuntu 16.04 x64
PhantomJS:beta-linux-ubuntu-xenial 2.1.1
Python 2.7.12
MacOS 10.12.1

目的

租了臺服務器當計算和運行平臺,主要用於分佈式網路爬蟲,有需要用到phantomjs的地方,網上資料比較少,自己花了點時間,整理了一下


安裝phantomjs(Ubuntu版本)

phantomjs下載地址,這裏根據自己系統版本進行下載,我的雲服務器是阿里的ESC,ubuntu

首先:apt-get update    # 更新軟件列表。
     apt-get upgrade   # 更新軟件。

其次再執行如下步驟     
步驟一下載包:wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.5.0-beta-linux-ubuntu-xenial-x86_64.tar.gz
步驟二解壓:tar -xzvf phantomjs-2.5.0-beta-linux-ubuntu-xenial-x86_64.tar.gz
步驟三切入路徑:cd phantomjs-2.5.0-beta-ubuntu-xenial/bin
步驟四:chmod +x phantomjs
步驟五查看是否生效:phantomjs -v  # 有信息如 2.1.1 則生效

安裝Phantomjs(MacOS版本)

步驟一下載包:去這裏下載對應版本http://phantomjs.org/download.html
步驟二解壓:雙擊就行,用unzip這都無所謂
步驟三切入路徑:cd ~/Downloads/phantomjs-2.1.1-macosx/bin  # 我下的路徑的路徑是download,版本不一,注意修改
步驟四:chmod +x phantomjs
步驟五: 配置環境,因爲我裝的的zsh,所以文件需要修改的是~/.zshrc這個文件,加上這句話export PATH="/Users/mrlevo/Downloads/phantomjs-2.1.1-macosx/bin/:$PATH",然後source ~/.zshrc 即可生效(沒用zsh的同學,直接修改的文件時~/.bash_profile,添加內容和上述一致)
查看是否生效:phantomjs -v  # 有信息如 2.1.1 則生效

phantomjs的使用(Ubuntu和MacOS都一樣)

給個栗子

>>> from selenium import webdriver  # pip install selenium
>>> driver_detail = webdriver.PhantomJS()
>>> driver_detail.get('https://www.baidu.com')
>>> news = driver_detail.find_element_by_xpath("//div[@id='u1']/a")
>>> print news.text
新聞
>>> driver_detail.quit() # 記得關閉,不然耗費內存

Ps.至於在win系統下的phantomjs操作,還需要加上一個執行路徑,畢竟在win上phantomjs是個可執行的exe

win上執行可參考Selenium+PhantomJS自動續借圖書館書籍(下)等等,我還是用過很多次win下的phantomjs的,比較爽


Pay Attention

QXcbConnection: Could not connect to display
PhantomJS has crashed. Please read the bug reporting guide at
http://phantomjs.org/bug-reporting.html and file a bug report.
Aborted

解決方案

步驟一:sudo apt-get install xvfb
步驟二:sudo xvfb-run wkhtmltopdf

xvfb 是通過提供一個類似 X server 守護進程 和 設置程序運行的環境變量 DISPLAY 來提供程序運行的環境,wkhtmltopdf,把HTML頁面內存轉換成PDF

如按照上述步驟還未解決,請重啓終端!


致謝

QXcbConnection: Could not connect to display Aborted
phantomjs資源下載

發佈了97 篇原創文章 · 獲贊 424 · 訪問量 92萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章