關於java獲取網頁內容


最近項目需求,做一些新聞站點的爬取工作。
1.簡單的jsoup爬取,靜態頁面形式;

String url="a.atimo.cn";//靜態頁面鏈接地址
Document doc = Jsoup.connect(url).userAgent("Mozilla").timeout(4000).get();
if(doc!=null){ Elements es = doc.select("div.comments>ul>li");// System.out.println(es); if(es!=null && es.size()>0){ for (Element element : es) { String link = element.select("div>h3").attr("href"); String title = element.select("div>h3").text(); String author = element.select("div.c-abstract>em").text(); String content = element.select("dd>a>div.icos>i:eq(1)").text(); } } }

通過jsop解析返回Document 使用標簽選擇器,選擇頁面標簽中的值,即可獲取頁面內容。

2.延時加載,有些網站存在延時加載,表格內容,或者嵌入頁面形式的加載的頁面;
屬於jsop范圍

        //構造一個webClient 模擬Chrome 瀏覽器
        String url = "https://www.cnblogs.com/atimo/";
        WebClient webClient = new WebClient(BrowserVersion.CHROME);
        //支持JavaScript
        webClient.getOptions().setUseInsecureSSL(true); 
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setTimeout(3000000);
        HtmlPage rootPage = webClient.getPage(url);
        String html = rootPage.asXml();
        Document document = Jsoup.parse(html);
        Elements es = document.select("div.comments");//.select("#content_left");
        System.out.println(es);
        if(es!=null && es.size()>0){
            for (Element element : es) {
            String link = element.select("div.f13>a").attr("href");
            String title = element.select("div>h3>a").text();
            String text = element.select("div.c-abstract>em").text();
        }
        }    

獲取到的是Document 使用標簽選擇器,選擇頁面標簽中的值,即可獲取頁面內容。

3.獲取評論或其他內容,返回json數據;js請求
普通請求,只需要使用
 HttpURLConnection connection = createRequest(url, "GET");
  
// 建立實際的連接 connection.connect();
 
發送GET請求過去json數據后解析即可;
4.js請求帶請求頭參數(部分為移動端請求)

            CloseableHttpClient https = HttpClients.createDefault();
            String url = "https://action=hene=124&devicetype=androidlag=zh_CN&nettyene=3&pass_ticwx_header=1";
            HttpGet httpPost = new HttpGet(url);
            httpPost.addHeader("Host", "mp.weixin.qq.com");
            httpPost.addHeader("x-wechat-uin", wechartCookie.getUin());
            httpPost.addHeader("x-", "參數");
            HttpResponse response = https.execute(httpPost);
            HttpEntity entitySort = response.getEntity();
            String html = EntityUtils.toString(entitySort, "utf-8");

 

請求頭參數根據抓包工具攔截的請求時需要的參數變更;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM