Jsoup的简单使用

jsoup是一款Java的HTML解析器,主要用来对HTML解析

导入依赖

<dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.3</version>
        </dependency>

Java代码

@Test
    void contextLoads2() throws IOException {
        String url = "https://sdrhser.baidu.com/s?id=1665515378178745245&wfr=spider&for=pc";
        Connection conn = Jsoup.connect(url).timeout(3000);
        //设置请求头,模拟浏览器登陆,绕过简单的反爬虫机制
        conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        conn.header("Accept-Encoding", "gzip, deflate, sdch");
        conn.header("Accept-Language", "zh-CN,zh;q=0.8");
        conn.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
        //从url中获取流并解析为Document对象
        Document document = conn.get();
        Elements elements = document.getElementsByClass("img-container");
        for (Element element : elements) {
            Elements img = element.getElementsByTag("img");
            for (int i = 0; i < img.size(); i++) {
                String src = img.eq(i).attr("src");
                System.out.println(src);
            }
        }
    }

爬取结果如下

2020-10-18 21:25:49.011  INFO 10732 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-10-18 21:25:49.032  INFO 10732 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-10-18 21:25:49.058  INFO 10732 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2020-10-18 21:25:49.244  INFO 10732 --- [           main] c.l.s.Springboot01ApplicationTests       : Started Springboot01ApplicationTests in 11.456 seconds (JVM running for 14.219)
https://pics0.baidu.com/feed/32fa828ba61ea8d3556bfacb2147a948241f580c.jpeg?token=bbc10ca3cd821e69885f1a81aef2daec
https://pics5.baidu.com/feed/77c6a7efce1b9d16853f6a2c4b932d898d546453.jpeg?token=a295597413f075effa421cc8fa8d0c9f
https://pics1.baidu.com/feed/1f178a82b9014a90716d5eb21e3aa014b21beec6.jpeg?token=930c3d827d17beeea3af30a7020889b3
https://pics4.baidu.com/feed/2cf5e0fe9925bc310e80c38de69214b7ca13709e.jpeg?token=9e0b4a5da4ef4e38e0404a64e31329ee&s=015031D1989F7BDAD808D4030100E0E0
https://pics0.baidu.com/feed/dcc451da81cb39dbd26674f1675b9022aa183042.jpeg?token=5f98e36fc80f71a9a52f425ae627e267
https://pics7.baidu.com/feed/1ad5ad6eddc451da66a199ed0eb0cb60d0163231.jpeg?token=94fd543c08af98f7c4e7e97f0282197f
https://pics2.baidu.com/feed/2934349b033b5bb59f4ea562819e4c3fb700bc61.jpeg?token=8ace1a88c84b14f5f0977ac7223ed139
https://pics6.baidu.com/feed/0dd7912397dda144c2d1f7c604fa49a40df486ba.jpeg?token=b4bf13fcedd4cf61a1506e6df42fa55b
https://pics0.baidu.com/feed/203fb80e7bec54e70f03d6ef0c7502564ec26a2c.jpeg?token=43ffb710ca0798241285ff4363d49dfc
https://pics0.baidu.com/feed/730e0cf3d7ca7bcbc96edc120644f265f624a84e.jpeg?token=539ed150f7f5a9b567af603967725a4b
https://pics6.baidu.com/feed/dc54564e9258d109a701dd8a661555b96d814dff.jpeg?token=2f645183b556ee55a04404cef1b494f1
https://pics0.baidu.com/feed/908fa0ec08fa513d68d7cd0a8b20ccfdb3fbd9bd.jpeg?token=e337fa4827d9918ebc8440b59136766f
https://pics2.baidu.com/feed/279759ee3d6d55fb68a348dbda6fd64c21a4ddbe.jpeg?token=88e22981f76e465b49aefb4f5cbc821f
https://pics4.baidu.com/feed/6c224f4a20a446237366e1442f6feb080cf3d738.jpeg?token=ae4f0c3a5f2833a51c3555bd6939fa25
https://pics3.baidu.com/feed/f7246b600c3387441a261261e94240ffd62aa0a4.jpeg?token=1014225dcef5966735961c089113f529
2020-10-18 21:25:50.416  INFO 10732 --- [extShutdownHook] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'
2020-10-18 21:25:50.418  INFO 10732 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-10-18 21:25:50.475  INFO 10732 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource   : {dataSource-0} closing ...

Process finished with exit code 0

Jsoup+httpclient 模拟登陆和抓取页面 package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String css = "http://user.goodjobs.cn/personal.css"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); ////////////////////////////body////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////link////////////////////////// Elements links = doc.select("link");//对link标签有href的路径都作处理 for (Element link : links) { String hrefAttr = link.attr("href"); if (hrefAttr.contains("/personal.css")) { hrefAttr = hrefAttr.replace("/personal.css",css); Element hrefVal=link.attr("href", hrefAttr);//修改href的属性值 sb.append(hrefVal.toString()).append("\n"); } } ////////////////////////////script////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////script////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); BufferedReader in = new BufferedReader(new FileReader(infile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content = sb.toString(); out.write(content); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗罗的1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值