java 爬虫Demo

package com.iminer.crawlers.gsdata;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.iminer.crawlers.CrawlerUtils4MusicAndMovie;

public class Test {
	
	static String url = "http://www.gsdata.cn/index.php/rank/ranks?gid=@GID@&date=2015-09-22&page=1";
	static String detailurl = "http://www.gsdata.cn/index.php/rank/single?id=";

	
	public static void main(String[] args) throws Exception {
		WebClient webClient = CrawlerUtils4MusicAndMovie.getClient();
		String entranceUrl  ="http://www.gsdata.cn/index.php/rank/detail?gid=0";
		HtmlPage page = webClient.getPage(entranceUrl);
		List<?> byXPath = page.getByXPath("//ul[@class='group-items']/li");
		List<String> gids = new ArrayList<String>();
		
		for (Object object : byXPath) {
			HtmlElement oElement = (HtmlElement) object;
			String attribute = oElement.getAttribute("data-gid");
			gids.add(attribute);
		}

		for (String gid : gids) {
			String tempUrl  = url.replace("@GID@", gid);
			webClient.addRequestHeader("X-Requested-With", "XMLHttpRequest");
			UnexpectedPage spage = webClient.getPage(tempUrl);
			JSONObject jsonObject = JSONObject.fromObject(spage.getWebResponse().getContentAsString());
			String total = jsonObject.getJSONObject("data").getString("total");
			System.out.println(total);
			JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("rows");
			for (Object object : jsonArray) {
				JSONObject jsonObject2 = (JSONObject) object;
				String id = jsonObject2.getString("nickname_id");
				String temptempurl = detailurl + id;
				System.out.println(temptempurl);
				
				//详细页的访问
				HtmlPage page2 = webClient.getPage(temptempurl);
				List<?> byXPath2 = page2.getByXPath("//li[@class='li_2']");
				for (Object object2 : byXPath2) {
					HtmlElement element = (HtmlElement) object2;
					System.out.println(element.getTextContent());
				}
				
				//访问统计数据
				//http://www.gsdata.cn/index.php/rank/singleStatistic?id=52
				
				
			}
			
			
			
		}
		
		

		
		
		
		
	}
	
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值