背景:公司項目要對接第三方商城的商品到本身的商城來賣,商品詳情給了個連接url,由於對方的商品詳情有他們的物流說明,售後信息,因此要求去掉這部分的代碼php
@Test public void getItemDetail() throws IOException { String url="https://www.xxx.com";//此處url做了處理,不能提供真實url,防止泄密,侵權,你們能夠本身找一個url來完 String itemDetail = getItemDetail(url); System.out.println(itemDetail); } private String getItemDetail(String url){ //思路:經過請求獲取html文本,經過選擇器找到對應的標籤,而後找到該標籤的父標籤,最後將父標籤移除 String itemDetailHtml = NetUtil.httpGet(url, Maps.newHashMap());//獲取商品詳情 if(StringUtils.isBlank(itemDetailHtml)){ return null; } Document parse = Jsoup.parse(itemDetailHtml); //也能夠直接使用url來解析,下面註釋所示 //URL linkUrl = new URL(url); // Document parse=Jsoup.parse(linkUrl,5000); if(parse==null){ return null; } //幹掉頭部圖片 //Jsoup強大之處在於能夠使用css選擇器,但要注意img[src='http://www.konvy.com/static/team/Banner/3.jpg'],屬性值這裏加了引號,這樣會取不到值,下面纔是正確的 Elements topImgEls = parse.select("img[src=http://www.konvy.com/static/team/Banner/3.jpg]"); //頭部url if(null!=topImgEls && topImgEls.size()>=1){ Element topImgEl = topImgEls.get(0);//獲取第一個元素 Element topPEL = topImgEl.parent();//獲取該img標籤的父標籤P標籤 topPEL.remove();//整個p標籤移除,元素能夠將本身從整個document中移除 } //幹掉底部圖片 Elements aEls= parse.select("a[href=http://www.konvy.com/account/signup.php]");//底部第一張圖片 if(null!=aEls && aEls.size()>=1){ Element aEL = aEls.get(0);//獲取底部a標籤 Element pBottom1 = aEL.parent();//獲取底部a標籤的父標籤P pBottom1.remove();//底部標籤本身移除本身 } Elements imgElsBottom = parse.select("img[src=http://www.konvy.com/static/team/Banner/shipping%2024h.jpg]");//底部第二張圖片 if(null!=imgElsBottom && imgElsBottom.size()>0){ Element imgBttom = imgElsBottom .get(0); //底部第二張圖片 Element pBottom2 = imgBttom.parent();//底部第二張圖片的父標籤 pBottom2.remove();//底部第二張圖片的父標籤進行移除 } return parse.toString(); }
依賴:<dependency>
<groupId>org.jsoup</groupId>
<artifactId>com.springsource.org.jsoup</artifactId>
<version>1.5.2</version>
</dependency>
css