詳細なチュートリアル:crawler4jクロールJingdong商品情報Javaクローラーcrawler4jチュートリアルの概要



Detailed Tutorial Crawler4j Crawling Jingdong Commodity Information Introduction Java Crawler Crawler4j Tutorial



より人気のあるクロール言語は、Java、paython、c言語です。著者はJava言語を学んでいるので、Javaを使用してWebページ情報をクロールする方法を紹介します。

最も原始的なJavaクローラーのデモから始めて、crawler4jフレームワークを使用してクロールする方法を見てみましょう。



デモ

JavaのUrlオブジェクトを使用して、URLをポイントし、接続を確立し、入力ストリームを取得し、ストリーム内の情報を解析します。デモにはjdkのみが必要であり、他のjarパッケージを導入する必要はありません。以下のソースコードを参照してください。



public static void main(String[] args) throws IOException { //Create a new url object and pass in the url value through the constructor URL url = new URL('https://www.jd.com/') //Establish a connection between Java and url, which is equivalent to our access to the URL, the difference is that Java returns the connection and what we return to the naked eye is the content of the webpage HttpURLConnection connection = (HttpURLConnection) url.openConnection() //Judging whether the access is successful through the corresponding status code int code = connection.getResponseCode() if (code != 200) { return } //Get an input stream after the connection accesses the webpage, which contains the information content of the webpage InputStream stream = connection.getInputStream() //Get the information in the stream through BufferedReader BufferedReader reader = new BufferedReader(new InputStreamReader(stream, 'utf-8')) //Output information String r = null while ((r = reader.readLine()) != null) { System.out.println(r) } }

ここでのURLは、jd.comだけでなくhttpプロトコルで渡す必要があります。そうしないと、例外が報告されます。

Exception in thread 'main' java.net.MalformedURLException: no protocol: jd.com

出力を見てみましょう(コンテンツのごく一部のみが傍受されます):

Jingdong (JD.COM)-Genuine low price, quality assurance, timely delivery, easy shopping! window.pageConfig = { compatible: true, preload: false, navId: 'jdhome2016', timestamp: 1521683291000, isEnablePDBP: 0,, surveyTitle: 'Survey Questionnaire', surveyLink : '//surveys.jd.com/index.php?r=survey/index/sid/889711/newtest/Y/lang/zh-Hans', leftCateABtestSwitch : 0, '' : '' }

この時点で、単純なクローラーが実装されています。原則は単純です:Urlオブジェクトを使用してURLをポイントし、接続を確立し、入力ストリームを取得し、ストリーム内の情報を解析し、取得した情報の内容に基づいて独自の需要情報をフィルターで除外します。もちろん、これらの数行のコードは私たちのニーズを満たすにはほど遠い可能性があるため、市場には多くのオープンソースのJavaクローラーフレームワークがあります。ナッチ、Heritrixクローラー4j待って、具体的な違いは何ですか、 ここをクリックしてください。



次に、トピック「crawler4jを使用して高速クロールする方法」に入ります。 githubソースのダウンロード



githubのソースコードとreadme.mdドキュメントによると、crawler4jを使用してすばやくクロールできます。英語で一定の基礎を持っているreadme.mdドキュメント

crawler4j is an open source web crawler for Java which provides a simple interface for crawling the Web. Using it, you can setup a multi-threaded web crawler in few minutes.

上記のように、クローラー4jこれは、マルチスレッドのクロールWebサイトプログラムをすばやく構築できるオープンソースのクローラーフレームワークであり、コーディングは数分以内に完了することができます。

最初の一歩:読者がMavenを使用したことがある場合は、Mavenのpomの紹介を簡単に使用できます。

onebeartoe onebeartoe https://repository-onebeartoe.forge.cloudbees.com/snapshot/ edu.uci.ics crawler4j 4.4-SNAPSHOT

Mavenを使用したことがない場合は、ソースコードをjarパッケージに入力してから、jarパッケージをインポートして使用する必要があります。

2番目のステップ:WebCrawlerから継承するクローラークラスを作成し、次のように2つのメソッドを書き直します。

public class MyCrawler2 extends WebCrawler { @Override public boolean shouldVisit(Page referringPage, WebURL url) { //The function of this method is to filter the URLs that you don't want to visit //return false when the url is filtered out and will not be crawled return super.shouldVisit(referringPage, url) } @Override public void visit(Page page) { //The function of this method is to call this method when the shouldVisit method returns true to get the page content, which has been encapsulated in the Page object super.visit(page) } }

3番目のステップ:コントローラークラスを作成し(実際にはどのクラスでもかまいません)、公式ドキュメントに従ってmainメソッドを作成し、変更するだけです。スレッド数とURLそれでおしまい。 URLはシードと呼ぶことができます。 URLが渡される限り、crawler4jはURLのコンテンツに従ってページ内のすべてのURLを取得し、何度も何度もクロールしますが、繰り返されるURLは繰り返しクロールされず、無限のループは発生しません。 。 。

public class Controller { public static void main(String[] args) throws Exception { String crawlStorageFolder = '/data/crawl/root'//File storage location int numberOfCrawlers = 7//number of threads CrawlConfig config = new CrawlConfig() config.setCrawlStorageFolder(crawlStorageFolder)//Configuration object settings PageFetcher pageFetcher = new PageFetcher(config) RobotstxtConfig robotstxtConfig = new RobotstxtConfig() RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher) CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer)//Create controller.addSeed('http://www.ics.uci.edu/~lopes/')//Incoming url controller.start(MyCrawler.class, numberOfCrawlers)//Start crawling } }

mainメソッドを開始して、Webページのクロールを完了します。

mavenメソッドを使用して上記のpomファイルのみをインポートすると、問題が発生し、起動時に常にエラーが報告されます。

Exception in thread 'main' java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy at com.chenyao.Controller.main(Controller.java:25) Caused by: java.lang.ClassNotFoundException: org.apache.http.ssl.TrustStrategy これは本当に不可解で、インターネットでこのエラーを検索しました。 2つのjarパッケージをインポートするだけで、バージョンが高くなる必要があります。 org.apache.httpcomponents httpcore 4.4 org.apache.httpcomponents httpclient 4.4.1

Jingdongの製品情報をクロールするには、以下の例を記述してください


1.コントローラー

public class Controller { public static void main(String[] args) throws Exception { String crawlStorageFolder = '/data/crawl/root'//File storage location int numberOfCrawlers = 1//number of threads CrawlConfig config = new CrawlConfig() config.setCrawlStorageFolder(crawlStorageFolder)//Configuration information setting PageFetcher pageFetcher = new PageFetcher(config) RobotstxtConfig robotstxtConfig = new RobotstxtConfig() RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher) CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer)//Create crawler executor Controller.addSeed('https://search.jd.com/Search?keyword=notebook&enc=utf-8&wq=notebook')//Incoming seed URL to crawl controller.start(MyCrawler2.class, numberOfCrawlers)//Start crawling

2.クローラークラス。ここでの2つの実装方法は特に重要です。コントローラは単なるアクセスエントリポイントです。特定のアクセスルールとアクセス結果はすべて、これら2つの方法で実装されます。

Jingdongでキーワード検索した後、htmlルールを確認し、製品がすべて

  • 鬼ごっこ

    拡大を続ける

  • タグを付けて、製品の特定の情報を確認します。ここで、作成者は画像リンクをクロールしますが、読者のニーズに応じて他の情報をクロールすることもできます。


    public class MyCrawler2 extends WebCrawler { //Custom filter rules private final static Pattern FILTERS = Pattern.compile('.*(\.(css|js|gif|jpg|png|mp3|mp4|zip|gz))$') @Override public boolean shouldVisit(Page referringPage, WebURL url) { String href = url.getURL().toLowerCase()//Crawled URL to lowercase //The URL to be filtered is defined here. My requirement is to crawl only the products in the page searched by JD. The URL needs to start with https://search.jd.com/search boolean b =!FILTERS.matcher(href).matches()&&href.startsWith('https://search.jd.com/search') return b } @Override public void visit(Page page) { String url = page.getWebURL().getURL() System.out.println(url) //Determine whether the page is a real web page if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData() String html = htmlParseData.getHtml()//page html content Document doc = Jsoup.parse(html)//Using jsoup to parse html, you will not be able to simply search this //When using the selector, you need to understand the html rules in the webpage, go to F12 in the webpage yourself, Elements elements = doc.select('.gl-item') if(elements.size()==0){ return } for (Element element : elements) { Elements img = element.select('.err-product') if(img!=null){ //Output picture link System.out.println(img.attr('src')) System.out.println(img.attr('data-lazy-img')) } } } } }

    結果を見てください:


    訪問しないのはフィルタリングされたURLです

    以下の出力は画像へのリンクです

    Crawler4jを使用すると非常に便利です。そして少しばかげています。読者は自分でWebページをクロールする楽しみを試すことができます