今日、同社は指定されたWebサイトでクエリをした後、いくつかのデータスクレイピングを行う必要があるため、デモの使用には時間がかかりました。
アイデアは非常に簡単です。Javaを介してリンクにアクセスし、HTML文字列を取得し、リンクなどの必要なデータを解析することです。技術的には、JSOUPはページの解析に便利です。もちろん、JSOUPは非常に便利でシンプルです。コードの1行だけで使用する方法を知ることができます。
document doc = jsoup.connect( "http://www.oschina.net/").data( "query"、 "java")// request parameters.useragent( "i 'm jsoup") // postメソッドを使用してURLにアクセスします
実装プロセス全体を以下に説明します。
1。解析する必要があるページを分析します。
ウェブサイト:http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicindexquery
ページ:
最初にこのページでクエリを実行します:要求されたURL、パラメーター、メソッドなどを観察します。
ここでは、組み込みの開発者ツール(ショートカットキーF12)を使用します。以下はクエリの結果です。
URL、方法、およびパラメーターを見ることができます。 URLの方法またはクエリを知った後、以下のコードを開始します。再利用して拡張するために、いくつかのクラスを定義しました。
1。ルール。Javaは、クエリURL、メソッド、パラメーションなどを指定するために使用されます。
パッケージcom.zhy.spider.rule; / ** *ルールクラス * * @author zhy * */ public classルール{/ ** * link */ private string url; / ** *パラメーターコレクション */ private string [] params; / ***パラメーターに対応する値*/ private string [] values; / ** *返されたHTMLの場合、最初のタイプを設定してください */ private string resultTagname。 / ** * class / id / selection * resulttagnameのタイプを設定し、デフォルトでid * / private int type = idに設定します。 / ** *get / post *requestのタイプ、デフォルトGet * / private int requestmoethod = get; public final static int get = 0; public final static int post = 1; public final static int class = 0; public final static int id = 1;パブリック最終静的int選択= 2; public rule(){} public rule(string url、string [] params、string [] values、string resulttagname、int型、int requestmoethod){super(); this.url = url; this.params = params; this.values = values; this.resulttagname = resterTagname; this.type = type; this.requestmoethod = requestmoethod; } public string geturl(){return url; } public void seturl(string url){this.url = url; } public string [] getParams(){return params; } public void setparams(string [] params){this.params = params; } public string [] getValues(){return値; } public void setValues(string [] values){this.values = values; } public string getResultTagname(){return resultTagname; } public void setResultTagname(string resterTagname){this.ResultTagname = resterTagname; } public int getType(){return type; } public void setType(intタイプ){this.type = type; } public int getRequestMoethod(){return requestMoethod; } public void setRequestmoethod(int requestmoethod){this.requestmoethod = requestmoethod; }}簡単に説明しましょう。このルールクラスでは、クエリプロセス中に必要なすべての情報を定義します。これにより、拡張機能とコードの再利用が容易になります。クロールする必要がある各Webサイトに一連のコードを書くことは不可能です。
2。必要なデータオブジェクト、現在リンクのみが必要です、linktepedata.java
パッケージcom.zhy.spider.bean; public class linktypedata {private int id; / ***リンクアドレス*/プライベート文字列linkhref; / ***リンクタイトル*/ private string linktext; / ***概要*/プライベート文字列の概要。 / ***コンテンツ*/プライベート文字列コンテンツ。 public int getid(){return id; } public void setid(int id){this.id = id; } public string getLinkHref(){return linkhref; } public void setlinkhref(string linkhref){this.linkhref = linkhref; } public string getLinkText(){return linktext; } public void setLinkText(string linktext){this.linktext = linktext; } public string getSummary(){return summary; } public void setSummary(string summary){this.summary = summary; } public string getContent(){return content; } public void setContent(string content){this.content = content; }} 3。コアクエリクラス:extractservice.java
パッケージcom.zhy.spider.core; java.io.ioexceptionをインポートします。 java.util.arraylistをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 javax.swing.plaf.textuiをインポートします。 org.jsoup.connectionをインポートします。 import org.jsoup.jsoup; Import org.jsoup.nodes.document; Import org.jsoup.nodes.element; Import org.jsoup.select.elements; com.zhy.spider.bean.linktypedataをインポートします。 com.zhy.spider.rule.ruleをインポートします。 com.zhy.spider.rule.ruleexceptionをインポートします。 com.zhy.spider.util.textutilをインポートします。 / ** * * @author zhy * */ public class extractservice {/ ** * @param rule * @return */ public static list <linktypedata> extract(ルールルール){//必要な検証を実行するルールvalidaterule(ルール);リスト<linktypedata> datas = new ArrayList <linktypedata>(); linktypedata data = null; try { / ** * parse rule * / string url = rule.geturl(); string [] params = rule.getParams(); string [] values = rule.getValues(); string resultTagname = rule.getResultTagname(); int type = rule.getType(); int requestType = rule.getRequestMoethod();接続conn = jsoup.connect(url); //クエリパラメーターを設定するif(params!= null){for(int i = 0; i <params.length; i ++){conn.data(params [i]、values [i]); }} //リクエストタイプのdocument doc = null;を設定します。 switch(requestType){case rule.get:doc = conn.timeout(100000).get();壊す;ケースルール:post:doc = conn.timeout(1000000).post();壊す; } //プロセスデータを返す要素results = new Elements(); switch(type){case rule.class:results = doc.getelementsbyclass(resultTagname);壊す;ケースルール:ID:要素result = doc.getElementByID(restrtagname); results.add(result);壊す;ケースルールの選択:results = doc.select(resultTagname);壊す;デフォルト:// restrtagnameが空の場合、ボディタグは削除されます(cextutil.isempty(restrumtagname)){result = doc.getelementsbytag( "body"); }} for(element result:results){elements links = result.getElementsBytag( "a"); for(要素リンク:リンク){//必須フィルター文字列linkhref = link.attr( "href");文字列linktext = link.text(); data = new linktypedata(); data.setlinkhref(linkhref); data.setLinkText(linkText); data.add(data); }}} catch(ioexception e){e.printstacktrace(); }データを返します。 } / ***渡されたパラメーターで必要な検証を実行します* / private static void validAterule(ルールルール){string url = rule.geturl(); if(textutil.isempty(url)){throw new RuleException( "URLは空にすることはできません!"); } if(!url.startswith( "http://")){throw new RuleException( "URLは間違っています!"); } if(rule.getParams()!= null && rule.getValues()!= null){if(rule.getParams()。lules.getValues()。length){shrow new rurexception( "パラメーターのキー値はキーと値の数と一致しません!"); }}}}} 4.例外クラスが使用されます:ReoleException.java
パッケージcom.zhy.spider.rule;パブリッククラスのrueleexceptionは、runtimeexception {public ruleexception(){super(); // TODO自動生成コンストラクタースタブ} public Ruleexception(Stringメッセージ、スロー可能な原因){super(message、cause); // TODO自動生成コンストラクタースタブ} public Ruleexception(String Message){super(message); // TODO自動生成コンストラクタースタブ} public Ruleexception(Throwable bause){super(cause); // TODO自動生成コンストラクタースタブ}} 5.最後に、これはテストです。ここでのテストには2つのWebサイトが使用され、さまざまなルールが使用されます。詳細については、コードをご覧ください。
パッケージcom.zhy.spider.test; java.util.listをインポートします。 com.zhy.spider.bean.linktypedataをインポートします。 com.zhy.spider.core.extractserviceをインポートします。 com.zhy.spider.rule.ruleをインポートします。 public class test { @org.junit.test public void getdatasbyclass(){rule rule = new Rule( "http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicindexquery"、new String "" Quer.enterprismation "" new String [] {"xingwang"、 "}、" cont_right "、rule.class、rule.post); list <linktypedata> extracts = extractservice.extract(extracts);} @org.junit.test public void getdatassquer(){ルールルールルール(http://www.11315/search "、new String {] {" xingwang "}、" div.gmn div.con-model "、rule.selection、rule.get); printf(linktypedata> datas){linktypedata datas){data.getLinkText());出力結果:
Shenzhen Netxing Technology Co.、Ltd。http://14603257.11315.com *****************************************************************巻きついインターネットカフェ#****************************************************** Xinxing Net City ************************************* Shaanxi Tongxing Network Information Co.、Ltd。Xi'an Branch#****************************************
最後に、Baiduニュースを使用してコードをテストします。これは、コードが普遍的であることを意味します。
/*** Baidu Newsを使用して、URLとキーワードのみを設定し、タイプを返します*/ @org.junit.test public void getdatasbycssqueryuserbaidu(){){"http://news.baidu.com/ns"、new String [] {"}、new String" Rule.get); List <LinkTypedata> Extracts = ExtractService.Extrad(ルール); printf(抽出); }リンク、キーワード、リクエストの種類のみを設定し、特定のフィルター条件を設定しません。
結果:特定のジャンクデータがあることは確かですが、必要なデータをrawっている必要があります。ルールセクションと、フィルタリング条件のさらなる制限を設定できます。
時間/ns?word = alipay&ie = utf-8&bs = alipay&sr = 0&cl = 2&rn = 20&tn = news&ct = 0&clk = sortbytime *********************************************************************************最初のバッチに4,000万を投資する複数の当事者との資金http://finance.ifeng.com/a/20140409/12081871_0.shtml ********************************************* news/ns?word=%E6%94%AF%E4%BB%98%E5%AE%9D+cont:2465146414%7C697779368%7C3832159921&same=7&cl=1&tn=news&rn=30&fm=sd *************************************** Baiduスナップショットhttp://cache.baidu.com/c?m=9D78D513D9D437AB4F9E91697D1CC0161D4381132BA7D3020CD0870FD33A541 B0120A1AC26510D19879E20345DFE1E4BEA876D26605F75A09BFD91782A6C1352F8A2432721A844A0FD019ADC 1452FC423875D9DAD0EE7CDB168D5F18C&P = C96EC64AD48B2DEF49BD9B780B64&NEWP = C4769A4790934EA95EA28E 281C4092695912C10E3DD796&user = baidu&fm = sc&query =%d6%a7%b8%b6%b1%a6&qid = a400f3660007a6c5&p1 = 1 ********************************************************************** openSSL脆弱性は多くのWebサイトが含まれます。 ********************************************* 26同じニュース/ns?word =%e6%94%af%e4%bb%98%e5%ae%9d+cont:3869124100&同じ= 26&cl = 1&tn = news&rn = 30&fmスナップショットhttp://cache.baidu.com/c?m=9F65CB4A8C8507ED4FECE7631050803743438014678387492AC3933FC239045C1C3AA5EC 677E4742CE932B2152F4174BED843670340537B0EFCA8E57DFB08F29288F2C367117845615A71BB8CB31649B666CF04FDEA44 A7ECFF25E5AAC5A0DA4323C044757E97F1FB4D7017DD1CF4&P = 8B2A970D95DF11A05AA4C32013&NEWP = 9E39C64AD450FA40FA40 BD9B7C5253D8304503C52251D5CE042ACC&USER = BAIDU&FM = SC&QUERY =%D6%A7%B8%B6%B1%A6&QID = A400F36660007A6C5&P1 = 2 ***************************************************** Yahoo Japanは、6月http://www.techweb.com.cn/ucweb/news/id/2025843からAlipayの支払いのサポートを開始します**************************************************************
欠点がある場合は、それらを指摘することができます。あなたがあなたに役立つと思うなら、それを試してみてください~~ハハ
ソースコードをダウンロードして、ここをクリックしてください。
上記は、Java Crawler Informationのrawりの例です。今後も関連情報を追加し続けます。このサイトへのご支援ありがとうございます!