最近做了一个项目需要抓取淘宝,天猫和京东商品的主图,虽然可以通过喵有券,阿里百川等都可以获取相应的信息,但是小编还是自己写了一下,不喜勿碰哈!
引入jsoup的依赖
<!--java HTML解析器-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
编写代码
-
抓取淘宝商品主图
- 代码如下:
/** * 淘宝商品主图与标题的抓取 * @throws Exception */ @Test public void test03() throws Exception { //获取链接内容 Document doc = Jsoup.parse(new URL("https://item.taobao.com/item.htm?spm=a230r.1.14.198.ed206404tTPCQL&id=583410555532&ns=1&abbucket=7#detail" ), 1000); //获取h3的标签并且class属性为tb-main-title Elements titleSelect = doc.select("h3[class=tb-main-title]"); //获取img的标签并且id为J_ImgBooth Elements imgSelect = doc.select("img[id=J_ImgBooth]"); //获取主图链接 String imgUrl = imgSelect.get(0).attr("src"); //获取商品标题 String title = titleSelect.get(0).text(); String[] split = doc.selectFirst("script").data().split("var"); System.err.println("商品主图:"+imgUrl); System.err.println("商品标题:"+title); }
- 抓取结果
商品主图://gd2.alicdn.com/imgextra/i4/3373074298/O1CN01srFV9n1hcWluk7kei_!!3373074298.jpg_400x400.jpg 商品标题:马丁靴男高帮潮男鞋冬季加绒新款百搭英伦风中帮工装真皮短靴子男
-
抓取天猫商品主图
- 代码如下:
/** * 天猫商品主图与标题的抓取 * @throws Exception */ @Test public void test04() throws Exception { Document doc = Jsoup.parse(new URL("https://detail.tmall.com/item.htm?id=627611068048&ali_trackid=1_82d7994bc36f03179643f066442073e3&spm=a230r.1.14.1" ), 100000); System.out.println(doc); Elements select = doc.select("img[id=J_ImgBooth]"); String imgUrl = select.get(0).attr("src"); String title = select.get(0).attr("alt"); System.err.println("商品主图:"+imgUrl); System.err.println("商品标题:"+title); }
- 抓取结果
商品主图://img.alicdn.com/imgextra/i2/2940298761/O1CN01CNCoyS2EaaYdZf1f3_!!2940298761.jpg_430x430q90.jpg 商品标题:秋季马丁靴男中帮2020新款潮流高帮男鞋真皮男士工装靴英伦风短靴
-
抓取京东商品主图
- 代码如下:
/** * 京东商品主图与标题的抓取 * * @throws Exception */ @Test public void test02() throws Exception { Document doc = Jsoup.parse(new URL("https://item.jd.com/57134539386.html" ), 100000); Elements select = doc.select("img[id=spec-img]"); String imgUrl = select.get(0).attr("data-origin"); String title = select.get(0).attr("alt"); System.err.println("商品主图:" + imgUrl); System.err.println("商品标题:" + title); }
- 抓取结果
商品主图://img11.360buyimg.com/n1/s350x449_jfs/t1/128746/4/16856/300041/5f9d3420E746b4563/1529c6f908e9955a.jpg!cc_350x449.jpg 商品标题:宾色新款冬季韩版潮流日系男士针织衫半高领毛衣纯色商务休闲青年男士保暖修身中领上衣服男装秋冬季 【半高领】深灰色 L