webmagic爬取图片

2023-11-06 23:20
文章标签 图片 爬取 webmagic

本文主要是介绍webmagic爬取图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

webmagic算是一个国人开发比较简单粗暴的爬虫框架,首页:http://webmagic.io/ 中文文档:http://webmagic.io/docs/zh/posts/ch2-install/

这次随便找了个小图片网站爬取(大网站没代理怕被封IP):http://www.mmonly.cc/ktmh/hzw/list_34_1.html

分析网站:
这里写图片描述
要获取这些主要内容的连接
这里写图片描述
获取下一页的地址
这里写图片描述
最后根据前面的地址进入详细页面获取图片和下一页的连接

按F12查看资源有什么共性然后分析抓取
这里写图片描述
可以通过鼠标右键copy->copy selector等等获取该元素在网页中的位置(爬虫框架支持select选择器)
这里写图片描述
可以这样快速定位需要找的元素代码在哪

上代码:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.da</groupId><artifactId>spider-pic</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-core</artifactId><version>0.7.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-extension</artifactId><version>0.7.3</version></dependency><dependency><groupId>us.codecraft</groupId><artifactId>webmagic-selenium</artifactId><version>0.7.3</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>3.0.1</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-server</artifactId><version>2.18.0</version></dependency></dependencies>
</project>

后面几个依赖还没弄清楚具体什么用
主程序:

package com.da.main;import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;public class PicProcessor implements PageProcessor {private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);@Overridepublic void process(Page page) {if (page.getUrl().toString().startsWith("http://www.mmonly.cc/ktmh/hzw/list_")) {// System.out.println(1);// 获取详情页面page.addTargetRequests(page.getHtml().$("div.item_t > div > div.ABox > a").links().all());// 获取下一页,倒数第个a标签page.addTargetRequest(page.getHtml().$("#pageNum > a:nth-last-child(2)").links().toString());} else if (page.getUrl().regex("http://www.mmonly.cc/ktmh/hzw/[\\d]+") != null) {// System.out.println(page.getUrl());// 下一页Selectable links = page.getHtml().$("#nl > a").links();if (links != null && links.toString() != "##")page.addTargetRequest(links.toString());// 抓取内容String img = page.getHtml().$("#big-pic p img").toString();if (img == "null")img = page.getHtml().$("#big-pic a img").toString();img = img.substring(img.indexOf("src=\"") + 5, img.length() - 2);// System.out.println(img);page.putField("img", img);}}@Overridepublic Site getSite() {return site;}public static void main(String[] args) {Spider.create(new PicProcessor()).addUrl("http://www.mmonly.cc/ktmh/hzw/list_34_1.html").addPipeline(new MyPipeline()).thread(5).run();}
}

主程序就用官方推荐的模版就行了,主要抓取逻辑在process方法里面,就是一些正则和选择器获取解析内容工作

最后如果要那下载图需要重写Pipeline方法,默认是控制台打印路径

package com.da.main;import com.da.utils.UrlFileDownloadUtil;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;public class MyPipeline implements Pipeline {@Overridepublic void process(ResultItems resultItems, Task task) {// System.out.println(resultItems.getRequest().getUrl());String url = resultItems.get("img").toString();UrlFileDownloadUtil.downloadPicture(url);}
}

下载工具类:

package com.da.utils;import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;public class UrlFileDownloadUtil {/*** 传入要下载的图片的url列表,将url所对应的图片下载到本地*/public static void downloadPictures(List<String> urlList, List<String> names) {String baseDir = "E:\\spider\\";URL url = null;for (int i = 0; i < urlList.size(); i++) {try {url = new URL(urlList.get(i));DataInputStream dataInputStream = new DataInputStream(url.openStream());FileOutputStream fileOutputStream = new FileOutputStream(new File(baseDir + names.get(i)));byte[] buffer = new byte[1024 * 50];int length;while ((length = dataInputStream.read(buffer)) > 0) {fileOutputStream.write(buffer, 0, length);}System.out.println("已经下载:" + baseDir + names.get(i));dataInputStream.close();fileOutputStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}public static void downloadPictures(List<String> urlList) {String baseDir = "E:\\spider\\";URL url = null;for (int i = 0; i < urlList.size(); i++) {try {String[] files = urlList.get(i).split("/");String name = files[files.length - 1];url = new URL(urlList.get(i));DataInputStream dataInputStream = new DataInputStream(url.openStream());FileOutputStream fileOutputStream = new FileOutputStream(new File(baseDir + name));byte[] buffer = new byte[1024 * 50];int length;while ((length = dataInputStream.read(buffer)) > 0) {fileOutputStream.write(buffer, 0, length);}System.out.println("已经下载:" + baseDir + name);dataInputStream.close();fileOutputStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}// 下载一张图片public static void downloadPicture(String u, String name) {String baseDir = "E:\\spider\\";URL url = null;try {url = new URL(u);DataInputStream dataInputStream = new DataInputStream(url.openStream());FileOutputStream fileOutputStream = new FileOutputStream(new File(baseDir + name));byte[] buffer = new byte[1024 * 50];int length;while ((length = dataInputStream.read(buffer)) > 0) {fileOutputStream.write(buffer, 0, length);}System.out.println("已经下载:" + baseDir + name);dataInputStream.close();fileOutputStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}// 下载一张图片public static void downloadPicture(String u) {String baseDir = "E:\\spider\\";URL url = null;String[] files = u.split("/");String name = files[files.length - 1];try {url = new URL(u);DataInputStream dataInputStream = new DataInputStream(url.openStream());FileOutputStream fileOutputStream = new FileOutputStream(new File(baseDir + name));byte[] buffer = new byte[1024 * 50];int length;while ((length = dataInputStream.read(buffer)) > 0) {fileOutputStream.write(buffer, 0, length);}System.out.println("已经下载:" + baseDir + name);dataInputStream.close();fileOutputStream.close();} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

这篇关于webmagic爬取图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/359657

相关文章

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

在服务器上浏览图片

@StarSky 2018-10-26 15:09 字数 15971 阅读 28 https://www.zybuluo.com/StarSky/note/1294871 来源 2018-09-27 线上服务器安装 imgcat Tool   2018-09-27 线上服务器安装 imgcat 0. 准备文件:iterm2_shell_integration.bash1. 在有权限

el-upload 上传图片及回显照片和预览图片,文件流和http线上链接格式操作

<div v-for="(info, index) in zsjzqwhxqList.helicopterTourInfoList" :key="info.id" >编辑上传图片// oss返回线上地址http链接格式:<el-form-itemlabel="巡视结果照片":label-width="formLabelWidth"><el-upload:action="'http:

【QML】用 Image(QQuickPaintedItem) 显示图片

大体功能: 频繁地往界面推送图片,帧率达到视频效果。捕获画布上的鼠标事件和键盘事件。 代码如下: // DrawImageInQQuickPaintedItem.pro 代码如下:QT += quick# You can make your code fail to compile if it uses deprecated APIs.# In order to do so, uncom

用Ps将PSD切片并将切片保存为透明背景的图片

第一步:选择放大镜工具或者Ctrl++将要切片的部分放大。 第二步:选择移动工具单击要切片的部分,在右边的图层栏找到要切片的图层在文字上右键选择转换为智能对象,再右键该图层的文字选择栅格化图层。 第三步:单击选中所要切片的部分,然后Ctrl+A、Ctrl+C、Ctrl+N(背景内容选择透明)、Ctrl+V、Ctrl+S(将文件保存为PNG格式),这样就可以得到透明背景的图片了!

Android性能优化系列之Bitmap图片优化

在Android开发过程中,Bitmap往往会给开发者带来一些困扰,因为对Bitmap操作不慎,就容易造成OOM(Java.lang.OutofMemoryError - 内存溢出),本篇博客,我们将一起探讨Bitmap的性能优化。 为什么Bitmap会导致OOM? 1.每个机型在编译ROM时都设置了一个应用堆内存VM值上限dalvik.vm.heapgrowthlimit,用来限定每个应用可

加载网络图片显示大图

1.将图片的uri列表和下标传给ImagePagerActivity public void imageBrower(int position, ArrayList<String> urls2) {Intent intent = new Intent(this, ImagePagerActivity.class); intent.putExtra(ImagePagerActivity

html标签转换成img图片

app 里的元素需要转换成图片 <script src="../assets/js/html2canvas.min.js"></script>$(function () {html2canvas(document.querySelector("#app"), {useCORS: true}).then(canvas => {layer.close(vm.layerIndex)var img =

Typora撰写Markdown文档上传到github上图片显示问题

OS:Windows 软件:Typora 相信很多人都有撰写Markdown文档的需求,在这里首先安利一下Markdown撰写利器---typora。 Typora支持多种快捷方式生成markdown语法,快速入门,排版整齐漂亮。 当我们向markdown中粘贴图片资源的时候,会自动提示保存图片到...  这时我们可以在存放markdown文档的地方建立一个assert或者pic静态资源文

Jupiter notebook显示数据和图片 备忘

import cv2 as cvimport numpy as np%matplotlib inline #将图片显示在页面内np.set_printoptions(threshold=np.inf) #显示大量数据 path = '/Users/yuanl/Desktop/test1.jpg'img = cv.imread('/Users/yuanl/Desktop/test1.jpg',