linux 環(huán)境下 Java 運行 selenium 無界面 chrome 環(huán)境設(shè)置

前言

《Java 中使用 selenium 和 chrome 瀏覽器下載動態(tài)網(wǎng)頁》 一文中,演示了如何在 window 環(huán)境下通過 selenium 和 chrome 來下載動態(tài)網(wǎng)頁。但是我們的爬蟲一般是運行在 linux 服務(wù)器上的。服務(wù)器上一般是沒有 GUI 環(huán)境的。無法打開 chrome 窗口界面。以前的時候,爬蟲系統(tǒng)是用一種無界面的瀏覽器 PhantomJS 來實現(xiàn)。但是現(xiàn)在因為 FireFox 、chrome 這些瀏覽器開始支持無頭模式后, PhantomJS 已經(jīng)停止更新了,所以現(xiàn)在推薦使用 FireFox 和 chrome 的無頭模式來替代 PhantomJS 了。所謂的無頭模式就是無界面運行模式,正好適合在 linux 服務(wù)器這種沒有 GUI 環(huán)境的情況下使用。

在 linux 環(huán)境下使用 selenium 驅(qū)動 chrome 需要安裝 chrome 瀏覽器和 chrome webdriver。下面在 centos 7 環(huán)境下展示應(yīng)該如何做。

安裝 google chrome

首先從地址 https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm 下載離線安裝包。然后執(zhí)行下面的命令安裝 chrome 需要的依賴包

yum install libX11 libXcursor libXdamage libXext libXcomposite libXi libXrandr gtk3 libappindicator-gtk3 xdg-utils libXScrnSaver liberation-fonts

然后執(zhí)行命令安裝 chrome

rpm -ivh google-chrome-stable_current_x86_64.rpm

完成后執(zhí)行下面的命令查看版本

[root@localhost ~]# google-chrome --version
Google Chrome 70.0.3538.110 

可以看出當前版本為 70 版本

安裝 chrome webdriver

和文章 《Java 中使用 selenium 和 chrome 瀏覽器下載動態(tài)網(wǎng)頁》 中一樣,找到支持 70 版本 chrome 的下載地址,下載 linux 平臺版本的文件 chromedriver_linux64.zip 即可

web driver 不同平臺

無頭模式 selenium chrome 調(diào)用程序樣例

還是以 《Java 中使用 selenium 和 chrome 瀏覽器下載動態(tài)網(wǎng)頁》 中的程序為基礎(chǔ),將他改造為無頭模式

        WebDriver webDriver = null;
        try {
            String url = "http://www.lxweimin.com/p/675ea919230e";
            ChromeOptions chromeOptions=new ChromeOptions();
            //設(shè)置 chrome 的無頭模式
            chromeOptions.setHeadless(Boolean.TRUE);
             //啟動一個 chrome 實例
            webDriver = new ChromeDriver(chromeOptions);
            //訪問網(wǎng)址
            webDriver.get(url);
            Document document = Jsoup.parse(webDriver.getPageSource());
            Element titleElement = document.selectFirst("div.article h1.title");
            Element authorElement = document.selectFirst("div.article div.author span.name");
            Element timeElement = document.selectFirst("div.article span.publish-time");
            Element wordCountElement = document.selectFirst("div.article span.wordage");
            Element viewCountElement = document.selectFirst("div.article span.views-count");
            Element commentCountElement = document.selectFirst("div.article span.comments-count");
            Element likeCountElement = document.selectFirst("div.article span.likes-count");
            Element contentElement = document.selectFirst("div.article div.show-content");
            if (titleElement != null) {
                System.out.println("標題:" + titleElement.text());
            }
            if (authorElement != null) {
                System.out.println("作者:" + authorElement.text());
            }
            if (timeElement != null) {
                System.out.println("發(fā)布時間:" + timeElement.text());
            }
            if (wordCountElement != null) {
                System.out.println(wordCountElement.text());
            }
            if (viewCountElement != null) {
                System.out.println(viewCountElement.text());
            }
            if (commentCountElement != null) {
                System.out.println(commentCountElement.text());
            }
            if (likeCountElement != null) {
                System.out.println(likeCountElement.text());
            }

            if (contentElement != null && contentElement.text() != null) {
                System.out.println("正文長度:" + contentElement.text().length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (webDriver != null) {
                //退出 chrome
                webDriver.quit();
            }
        }

和前文中的代碼相比,就是下面的地方不一樣

            ChromeOptions chromeOptions=new ChromeOptions();
            //設(shè)置 chrome 的無頭模式
            chromeOptions.setHeadless(Boolean.TRUE);
            //啟動一個 chrome 實例
            webDriver = new ChromeDriver(chromeOptions);

這個參數(shù)決定了是否用無頭模式來啟動
將程序打包并且上傳到 linux 服務(wù)器上,執(zhí)行命令

java -jar -Dwebdriver.chrome.driver=/data/deploy/chromedriver spider_demo-0.0.1-SNAPSHOT.jar 

控制臺會打印出下面的內(nèi)容

標題:是什么支撐了淘寶雙十一,沒錯就是它java編程語言。
作者:Java幫幫
發(fā)布時間:2018.08.29 14:49
字數(shù) 561
閱讀 632
評論 0
喜歡 4
正文長度:655

說明在 linux 用 java 通過 selenium 調(diào)用 chrome 訪問這個網(wǎng)頁成功了。如果沒有設(shè)置上面的無頭模式參數(shù),那么執(zhí)行的時候?qū)霈F(xiàn)下面的提示

org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  (Driver info: chromedriver=2.44.609551 (5d576e9a44fe4c5b6a07e568f1ebc753f1214634),platform=Linux 3.10.0-514.26.2.el7.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 399 milliseconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'iz2ze9kvzy03hms75m3jzlz', ip: '172.17.251.3', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-514.26.2.el7.x86_64', java.version: '1.8.0_171'
Driver info: driver.version: ChromeDriver
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
        at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
        at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
        at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
        at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
        at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
        at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
        at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
        at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
        at com.yanggaochao.spider.SpiderDemoApplication.run(SpiderDemoApplication.java:34)
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
        at com.yanggaochao.spider.SpiderDemoApplication.main(SpiderDemoApplication.java:21)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)

這樣,我們就可以在我們的爬蟲系統(tǒng)里面采用瀏覽器的方式下載網(wǎng)頁,實現(xiàn)所見即所得的下載效果。再也不用擔心動態(tài)渲染的網(wǎng)頁內(nèi)容無法下載了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,563評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,694評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,672評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,965評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,690評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,019評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,013評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,188評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,718評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,438評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,667評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,149評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,845評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,252評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,590評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,384評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內(nèi)容