java爬虫抓取网页搜索数据
首先访问这个使用必应并搜索想要的内容
https://www.bing.com/images/search?q=[把这里替换成想要的搜索内容]
按下f12来查看源码
我们可以找到a.iusc这个元素可以获取图片的源地址
注意,直接选中网页上的图片只能看到它的缩略图在哪。
由此可以编写出来爬虫脚本来下载指定搜索内容前几张
public static void downloadImage(String imgUrl, String fileName) throws Exception {
URL url = new URL(imgUrl);
URLConnection con = url.openConnection();
con.setConnectTimeout(10 * 1000);
InputStream is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
OutputStream os = new FileOutputStream(fileName);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
is.close();
}
public static void getImage(String keyword) {
String searchUrl = "https://www.bing.com/images/search?q=" + keyword;
try {
Document doc = Jsoup.connect(searchUrl).get();
Elements imgElements = doc.select("a.iusc"); // 获取存有原图链接的 a 标签
int count = 0;
for (Element imgElement : imgElements) {
String mData = imgElement.attr("m"); // 获取 m 属性中的 JSON 数据
// 使用正则解析 murl(高清图片 URL)
Pattern pattern = Pattern.compile("\"murl\":\"(.*?)\"");
Matcher matcher = pattern.matcher(mData);
if (matcher.find()) {
String imgUrl = matcher.group(1);
System.out.println("高清图片URL:" + imgUrl);
// 下载图片
downloadImage(imgUrl, "image" + count + ".jpg");
count++;
if (count >= 5) break; // 只下载前 5 张
}
}
} catch (Exception e) {
System.out.println("获取图片出错:" + e.getMessage());
}
}