java-selenium下載百度圖片

來源:互聯網
上載者:User

標籤:commons   comm   ons   turn   photo   img   jpg   size   https   

package download;import java.io.DataInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;import org.apache.commons.io.input.ReaderInputStream;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;public class Geturl {public static List<String> geturls(String baseUrl){List<String> urllist=new ArrayList<String>();System.setProperty("webdriver.chrome.driver", "E:\\\\webDriver\\\\chromedriverV2.28.exe");WebDriver driver = new ChromeDriver();driver.get(baseUrl);//擷取所有img標籤List<WebElement> imgList = driver.findElements(By.tagName("img"));System.out.println(imgList.size());try {Thread.sleep(10000);} catch (Exception e) {e.printStackTrace();}//便利所有標籤try {for (WebElement a : imgList) {//System.out.println(a.getText());System.out.println(a.getAttribute("src"));//擷取img標籤中的data-imgurl  data-imgurl//擷取img標籤data-imgurl屬性值String urlStr = a.getAttribute("src");/*if(urlStr.contains(".jpg")) {urllist.add(urlStr);}*/}} catch (Exception e) {e.printStackTrace();}return urllist;}public static void downloadImg(List<String> urllist) throws Exception{URL url=null;int imageNumber = 0;for(String urlString:urllist) {url = new URL(urlString);DataInputStream dis = new DataInputStream(url.openStream());String imageName ="C:\\Users\\0\\Pictures\\插畫\\photos"+ imageNumber +".jpg";FileOutputStream fos =new FileOutputStream(new File(imageName));byte[] buffer = new byte[1024];int length;while((length = dis.read(buffer))>0) {fos.write(buffer, 0, length);}dis.close();fos.close();imageNumber++;}}public static void main(String[] args) {List<String> urllist=geturls("https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gbk&word=%B2%E5%BB%AD&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111");System.out.println(urllist.size());try {downloadImg(urllist);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

  

java-selenium下載百度圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.