#爬虫# #selenium# #java# java 使用webDriver+selenium 抓取LOL英雄图片,再也不用下载了图片了。练会这个,想批量保存你喜欢的图片就可以直接保存了。
![fb18b01bb2542a17bf965161ab9a4484.png](https://i-blog.csdnimg.cn/blog_migrate/c5851e4b936f96486e855f8b38b0afa6.jpeg)
![9d0461b2a2a52f23720b9d85bd8b1221.png](https://i-blog.csdnimg.cn/blog_migrate/b7857da85019fd97b1bbb83d20d7d15c.jpeg)
今天复习了下seleniu,闲着无事就写了个爬虫小案例。
当然爬取之前要先了解一下协议,不要什么都爬。
爬虫是一门有趣的技术,它可以让我们感受到程序的魅力,给我们带来视觉冲击感和成就感,可以极大地提高我们对编程的学习兴趣。
愿你我,都能: 遵循君子协议 合理使用技术 提高学习兴趣
为什么每次被抓的都有你~
我们应该自觉遵守君子协议(爬虫协议的俗称),掌握爬虫的技术。
在对应网址之后增加 /robots.txt, 即可查看爬虫协议,知道哪些页面是不可爬取的,爬虫协议具体内容可自行bai度了解。
例如: https://www.baidu.com/robots.txt
![12c6202fcf1695990f2df3353dad989e.png](https://i-blog.csdnimg.cn/blog_migrate/5b4ad82b87ad20bc91045bc938d987b2.jpeg)
好,接下来进入主题:
1 先确定好模拟那个浏览器,需要下载对应浏览器的驱动。这里提供谷歌驱动。
http://chromedriver.storage.googleapis.com/index.html 打开此网址xia zai与谷歌浏览器版本基本一致的驱动。
2 模拟浏览器打开网页不难,抓取的难点在于拿到图片链接后怎样转化成图片并保存到本地。
3 学会了这一个简单的例子,然后我们想要抓取那个网站的图片就可以模拟写了。
然后就是编码了:直接贴代码 import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class seleniumTest3 {
static String baseUrl = "https://lol.qq.com/data/info-heros.shtml";
public static void main(String args[]) throws Exception
{
//创建文件夹
File file = new File("e://img");
if(!file.exists()) {
file.mkdir();
}
//创建一个webdriver
System.setProperty("webdriver.chrome.driver","G:ceshichromedriver_win32chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(baseUrl);
//获得所有a标签
List aList = driver.findElements(By.tagName("img"));
System.out.println(aList.size());
for (WebElement webElement : aList) {
if(webElement.getAttribute("src")!=null) {
String urlStr = webElement.getAttribute("src");
String name = webElement.getAttribute("alt");
System.out.println(webElement+" "+urlStr+" "+name);
// 新的图片文件名 = 编号 +"."图片扩展名
String newFileName = name+ ".png";
OutputStream os = new FileOutputStream(file.getPath()+""+newFileName);
// 构造URL
URL url = new URL(urlStr);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
InputStream is = con.getInputStream();
// 读取到的数据长度
int len;
byte[] bs = new byte[1024];
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
}
}
}
成果:
![f773487317db05851e2b008ed98f6fab.png](https://i-blog.csdnimg.cn/blog_migrate/d8c981627dccc5cb831fdc7d042b62ee.jpeg)
![ee5fca9f3bdc98de04c0e1d6cdca0e3f.png](https://i-blog.csdnimg.cn/blog_migrate/ffb5878ff0bd6dce0cbd2f69daf040aa.jpeg)
在爬虫的路上越走越好哈,有用的话支持下感谢