2017-02-08 3 views
0

私が見つけたのはthesethreepotential answersですが、それらはすべてHtmlUnit APIを使用しています。 HtmlUnit APIとonly use seleniumやブラウザ設定用の設定を使用しないようにするにはどうすればよいですか?セレン運転htmlunitでイメージを自動的にダウンロードさせるにはどうしたらいいですか?

+0

どのような画像がありますか?詳細を共有できますか? – Andersson

+0

画像タグで参照されている画像:。 – Vernon

+0

あなたは 'Java'のみで回答を受け入れますか? – Andersson

答えて

2

私が知る限り、HtmlUnit(セレンの有無にかかわらず)ですべての画像を自動的にダウンロードする方法はありません。あなたが投稿したリンクが示すように、次のコードを使用してページ上のすべての画像をダウンロードするにはHtmlUnitを強制することができます。

DomNodeList<DomElement> imageElements = htmlPage.getElementsByTagName("img"); 

for (DomElement imageElement : imageElements) { 

    HtmlImage htmlImage = (HtmlImage) imageElement; 

    try { 

     // Download the image. 
     htmlImage.getImageReader(); 
    } 
    catch (IOException e) { 
     // do nothing. 
    } 
} 

しかし、Selenium HtmlUnitDriverを使用した場合、現在のページを取得することは容易ではありません。複数の方法がありますが、すべてがprotectedHtmlUnitDriver.lastPage()メソッドにアクセスする必要があります。 One way to access this method is through reflection.もう1つの解決策は、protectedメソッドも同じパッケージ内のクラスからアクセスできるという事実を利用することです。packages can be the same across jars。後者の機能やデザインの欠陥を組み合わせることで、私は反射を避けるソリューションを考え出すことができました。代わりに、通常のクラスをHtmlUnitDriver --- org.openqa.selenium.htmlunitと同じパッケージに追加するだけです。

package org.openqa.selenium.htmlunit; 

import java.io.IOException; 

import com.gargoylesoftware.htmlunit.html.DomElement; 
import com.gargoylesoftware.htmlunit.html.DomNodeList; 
import com.gargoylesoftware.htmlunit.html.HtmlImage; 
import com.gargoylesoftware.htmlunit.html.HtmlPage; 

public class HtmlUnitUtil { 

    private HtmlUnitUtil() { 
     throw new AssertionError(); 
    } 

    public static void loadImages(HtmlUnitDriver htmlUnitDriver) { 

     // Since we are in the same package (org.openqa.selenium.htmlunit) 
     // as HtmlUnitDriver, we can access HtmlUnitDriver's protected 
     // lastPage() method. 
     HtmlPage htmlPage = (HtmlPage) htmlUnitDriver.lastPage(); 
     DomNodeList<DomElement> imageElements = 
      htmlPage.getElementsByTagName("img"); 

     for (DomElement imageElement : imageElements) { 

      HtmlImage htmlImage = (HtmlImage) imageElement; 

      try { 

       // Download the image. 
       htmlImage.getImageReader(); 
      } 
      catch (IOException e) { 
       // do nothing. 
      } 
     } 
    } 
} 

残念ながら、画像を読み込むたびにこのコードを手動で呼び出す必要があります。 HtmlUnitDriverの機能要求(htmlunit-driver #40)を作成して、画像を自動的にダウンロードするオプションを追加しました。この機能をご希望の場合は、その問題に投票してください。

3

これは、HtmlUnit 2.25-snapshotの一部です(webClient.getOptions().setDownloadImages(true))。

HtmlUnit-Driver 2.25スナップショット機能DOWNLOAD_IMAGES_CAPABILITYまたはhtmlUnitDriver.setDownloadImages(true)

関連する問題