当用户请求图片时,我们可以直接从其他网站的接口爬取。
Jsoup解析库可以根据html文档的元素,简单方便地获取内容。
maven依赖:
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
</dependency>
<!-- https://hutool.cn/docs/index.html#/-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>
演示:
准备工作:
以bing的图片搜索为例,我们在图片栏下搜索关键字,bing会给出很多卡片结果,打开开发者模式,光标对着卡片慢慢移动,直到选取到我们足够需要的内容。
这里笔者需要抓取图片和对应的描述,如上图所示,有一个class样式为{.iuscp.isv}的div盒子顺利包括了我们所需要的内容。
我们在右侧中选择添加样式,将{.iuscp.isv}样式添加进来,然后光标选取该样式,可以发现浏览器将所有的猫咪信息卡片都选取上了,可以证明我们需要的信息都在该class样式的div盒子中。
光有这些还不行,我们需要爬取的是bing搜索结果卡片的图片url还有描述字段,我们接着看html。
当我们选取卡片的图片内容时,可以看到class为{.iusc}的盒子中,有一个m属性,m属性有恰好有很多不同格式大小的图片url可以选取。
“描述”的文本也按这个方式寻找:
综上:
我们应该在搜索结果的html文档中,去每个class样式为{.iuscp.isv}的div盒子中,将其中的class为{.iusc}的盒子的m属性、class为{.inflnk}的盒子的aria-label属性取出来。
实例测试代码:
@SpringBootTest
public class CrawlerText {
@Resource
private PostService postService;
@Test
void testDynamicFetch() throws IOException {
int current = 1;
// 拼接爬取的地址
String url = "https://cn.bing.com/images/search?q=%E7%8C%AB%E5%92%AA&form=HDRSC2&first=" + current;
Document document = Jsoup.connect(url).get();
// System.out.println(document);
Elements elements = document.select(".iuscp.isv");
// System.out.println(elements);
List<Picture> picRes = new ArrayList<>();
for (Element element : elements) {
// 取图片地址(url)
// 取iuscp isv元素的第一个(get0).iusc类的元素的属性m的信息
String picUrl = element.select(".iusc").get(0).attr("m");
Map<String, Object> map = JSONUtil.toBean(picUrl, Map.class);
String mUrl = (String) map.get("murl");
// System.out.println(mUrl);
// 取标题
String title = element.select(".inflnk").get(0).attr("aria-label");
// System.out.println(title);
Picture pic = new Picture();
pic.setUrl(mUrl);
pic.setTitle(title);
picRes.add(pic);
}
System.out.println(picRes);
}
}