jsoup 爬虫 反爬虫

本人最近在研究爬虫和反爬虫技术,刚刚入坑,大佬勿喷。

一开始在网上找了一些资料,jsoup可以用于爬取页面,比较方便,但是现在很多商业项目特别是商城类得网站,都是先到页面再

异步请求数据的,没办法,那就拿到页面and脚本之后截取出请求url,再连接一遍,但是这里出现了我的知识盲区,反爬虫,

貌似狮子啊referre里面加入了加密token 难道在这就搞不定了吗?(代码如下)

String input = "新品";
        // 需要爬取商品信息的网站地址
        String url = "https://list.tmall.com/search_product.htm?q=" + input;
        // 动态模拟请求数据
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        // 模拟浏览器浏览(user-agent的值可以通过浏览器浏览,查看发出请求的头文件获取)
        httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
        CloseableHttpResponse response = httpclient.execute(httpGet);
        // 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        try {
            HttpEntity entity = response.getEntity();
            // 如果状态响应码为200,则获取html实体内容或者json文件
            if(statusCode == 200){
                String html = EntityUtils.toString(entity, Consts.UTF_8);
                // 提取HTML得到商品信息结果
                Document doc = null;
                // doc获取整个页面的所有数据
                doc = Jsoup.parse(html);
                //输出doc可以看到所获取到的页面源代码
//              System.out.println(doc);
                // 通过浏览器查看商品页面的源代码,找到信息所在的div标签,再对其进行一步一步地解析
                Elements ulList = doc.select("div[class='view grid-nosku']");
                Elements liList = ulList.select("div[class='product']");
                
                // 循环liList的数据(具体获取的数据值还得看doc的页面源代码来获取,可能稍有变动)
                for (Element item : liList) {
                    // 商品ID
                    String id = item.select("div[class='product']").select("p[class='productStatus']").select("span[class='ww-light ww-small m_wangwang J_WangWang']").attr("data-item");
                    System.out.println("商品ID:"+id);
                    // 商品名称
                    String name = item.select("p[class='productTitle']").select("a").attr("title");
                    System.out.println("商品名称:"+name);
                    // 商品价格
                    String price = item.select("p[class='productPrice']").select("em").attr("title");
                    System.out.println("商品价格:"+price);
                    // 商品网址
                    String goodsUrl = item.select("p[class='productTitle']").select("a").attr("href");
                    System.out.println("商品网址:"+goodsUrl);
                    // 商品图片网址
                    String imgUrl = item.select("div[class='productImg-wrap']").select("a").select("img").attr("data-ks-lazyload");
                    System.out.println("商品图片网址:"+imgUrl);
                    // http://detail.tmall.com/item.htm?id=574828937953&skuId=3933140994054&user_id=3708304089&cat_id=2&is_b=1&rn=fa473d406b1f3e784301d9b8c6c69b99
                    System.out.println("------------------------------------");
                    
                    //进入商品网址
                    String urlsp= "https:"+goodsUrl;
                    Document docsp = Jsoup.connect(urlsp)
                              .data("query", "Java")
                              .userAgent("Mozilla")
                              .cookie("auth", "token")
                              .timeout(3000)
                              .post();
                    //得到所有页面信息
                    String htmlsp = docsp.toString();
                    //从页面js脚本中截取出get请求的地址 ,这里面有具体的商品信息json数据
                    String  msgurl=htmlsp.substring(htmlsp.indexOf("url='")+5,htmlsp.indexOf("',isg"));
                    
                      //模仿异步请求获取商品信息
                     msgurl= "https:"+msgurl;
                     System.out.println("开始访问"+msgurl);
                     //这里输出的地址是: https://mdskip.taobao.com/core/initItemDetail.htm?isUseInventoryCenter=false&cartEnable=true&service3C=false&isApparel=true&isSecKill=false&tmallBuySupport=true&isAreaSell=false&tryBeforeBuy=false&offlineShop=false&itemId=574828937953&showShopProm=true&isPurchaseMallPage=false&itemGmtModified=1586754483000&isRegionLevel=false&household=false&sellerPreview=false&queryMemberRight=true&addressLevel=2&isForbidBuyItem=false
                     
                     String docmsg = Jsoup.connect(urlsp)
                             .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36")
                              .data("query", "Java")
                              .userAgent("Mozilla")
                              .cookie("auth", "token")
                              //这里没办法  模仿它的referrer也没有用  直接通过浏览器的结果是403无权访问  代码访问得到的结果不是json而是一个奇怪的页面html
                              .referrer("https://detail.tmall.com/item.htm?id=574828937953&skuId=3933140994054&user_id=3708304089&cat_id=2&is_b=1&rn=345a2fbc9e48e23851639f4739ca80b3")
                              .timeout(3000).execute().body();
//                    System.out.println(docmsg);
                    
                    break;//这里只找一个测试一下
                }
                    // 消耗掉实体
                    try {
                        EntityUtils.consume(response.getEntity());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    // 消耗掉实体
                    try {
                        EntityUtils.consume(response.getEntity());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

   商品详情的地址是

 http://detail.tmall.com/item.htm?id=574828937953&skuId=3933140994054&user_id=3708304089&cat_id=2&is_b=1&rn=fa473d406b1f3e784301d9b8c6c69b99
异步请求获取json数据的地址是
https://mdskip.taobao.com/core/initItemDetail.htm?isUseInventoryCenter=false&cartEnable=true&service3C=false&isApparel=true&isSecKill=false&tmallBuySupport=true&isAreaSell=false&tryBeforeBuy=false&offlineShop=false&itemId=574828937953&showShopProm=true&isPurchaseMallPage=false&itemGmtModified=1586754483000&isRegionLevel=false&household=false&sellerPreview=false&queryMemberRight=true&addressLevel=2&isForbidBuyItem=false

直接浏览器访问第二个会403权限不够

代码里访问又会给我返回一个器官的html页面,我认为原因主要是我的请求头没伪装好,但是由于对请求头不够了解,不知道哪些是必须的,哪些是它们系统自己设置的,崩溃了,有没有感兴趣的大佬帮我研究一下给个答案,感激不尽!
版权声明:本文为yangbaocai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yangbaocai/p/13056414.html