java之jsoup爬虫
生活随笔
收集整理的這篇文章主要介紹了
java之jsoup爬虫
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
準(zhǔn)備工作
https://pvp.qq.com/web201605/herolist.shtml
打開(kāi)開(kāi)發(fā)者工具(右鍵檢查),找到Elements定位到圖片的區(qū)域
通過(guò)Jsoup類(lèi)中靜態(tài)方法connect()連接網(wǎng)址https://pvp.qq.com/web201605/herolist.shtml
通過(guò)Connection對(duì)象獲取Document對(duì)象(即文檔對(duì)象)
通過(guò)Document對(duì)象獲取標(biāo)簽Elements對(duì)象
遍歷所有的li標(biāo)簽,得到該英雄的圖片地址
通過(guò)獲取所有得到的新地址,再通過(guò)定位得到圖片對(duì)應(yīng)的jpg格式
通過(guò)輸入輸出流將圖片讀取到本地
代碼
public class TestMain {public static void crawlingPictures() throws IOException {//連接網(wǎng)址Connection connect = Jsoup.connect("https://pvp.qq.com/web201605/herolist.shtml");//獲取網(wǎng)址的Document對(duì)象Document document = connect.get();//獲取照片的ul中class標(biāo)簽Elements byClass = document.getElementsByClass("herolist clearfix");//通過(guò)ul中class標(biāo)簽中的li標(biāo)簽獲取照片的地址Elements li = byClass.select("li");//循環(huán)遍歷每一個(gè)li標(biāo)簽的照片地址for (Element element : li) {//找到li中的a標(biāo)簽Elements a = element.getElementsByTag("a");//通過(guò)a標(biāo)簽中的href屬性獲取相應(yīng)的值String hrefs = a.attr("href");//拼接成一個(gè)完整的圖片新地址String path="https://pvp.qq.com/web201605/"+hrefs;//獲取照片text中的名字String text = a.text();//通過(guò)新照片地址打開(kāi)另一個(gè)網(wǎng)址(拼接好的英雄圖片地址)Connection connection = Jsoup.connect(path);//獲取新照片地址的Document對(duì)象Document doc = connection.get();//獲取照片div中的class對(duì)象Elements picclass = doc.getElementsByClass("zk-con1 zk-con");//獲取div中的屬性styleString attr = picclass.attr("style");//截取屬性值的字符串表示形式String substring = attr.substring(attr.indexOf("'") + 1, attr.lastIndexOf("'"));//拼接成一個(gè)URL的照片地址String newUrl="https:"+substring;//通過(guò)拼接好的字符串構(gòu)建成URL對(duì)象URL url=new URL(newUrl);//InputStream inputStream = url.openStream();byte[] bytes=new byte[1024];//通過(guò)URL打開(kāi)輸入流讀取數(shù)據(jù)BufferedInputStream bis=new BufferedInputStream(url.openStream());int read =bis.read(bytes);//通過(guò)輸出流寫(xiě)入圖片數(shù)據(jù)BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\下載\\test\\"+text+".jpg"));//讀取的數(shù)據(jù)不為-1while (read!=-1){//寫(xiě)入本地bos.write(bytes,0,read);bos.flush();read=bis.read(bytes);}//關(guān)閉流操作bos.close();bis.close();bis.close();}}public static void main(String[] args) {try {crawlingPictures();} catch (Exception e) {e.printStackTrace();}} }**測(cè)試結(jié)果,讀取完畢 **
總結(jié)
以上是生活随笔為你收集整理的java之jsoup爬虫的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 自己的路 php,生活感悟的句子:走自己
- 下一篇: 优秀项目解析:区块链上的房地产交易