溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Web抓取框架JSoup怎么用

發(fā)布時(shí)間:2021-11-30 17:50:44 來(lái)源:億速云 閱讀:122 作者:小新 欄目:編程語(yǔ)言

這篇文章主要介紹了Web抓取框架JSoup怎么用,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

僅供參考學(xué)習(xí)。

Web抓取框架

就像許多現(xiàn)代科技一樣,從網(wǎng)站提取信息這一功能也有多個(gè)框架可以選擇。最流行的有JSoup、HTMLUnit和Selenium WebDriver。這篇文章討論JSoup。

JSoup

JSoup是個(gè)開源項(xiàng)目,提供強(qiáng)大的數(shù)據(jù)提取API??梢杂盟鼇?lái)解析給定URL、文件或字符串中的HTML。它還能操縱HTML元素和屬性。

使用JSoup解析字符串

解析字符串是JSoup的最簡(jiǎn)單的使用方式。

public class JSoupExample {

    public static void main(String[] args) {

        String html = "<html><head><title>Website title</title></head><body><p>Sample paragraph number 1 </p><p>Sample paragraph number 2</p></body></html>";
        Document doc = Jsoup.parse(html);

        System.out.println(doc.title());

        Elements paragraphs = doc.getElementsByTag("p");

        for (Element paragraph : paragraphs) {

            System.out.println(paragraph.text());

        }

    }

這段代碼非常直觀。調(diào)用parse()方法可以解析輸入的HTML,將其變成Document對(duì)象。調(diào)用該對(duì)象的方法就能操縱并提取數(shù)據(jù)。

在上面的例子中,我們首先輸出頁(yè)面的標(biāo)題。然后,我們獲取所有帶有標(biāo)簽“p”的元素。然后我們依次輸出每個(gè)段落的文本。

運(yùn)行這段代碼,我們可以得到以下輸出:

Website title

Sample paragraph number 1

Sample paragraph number 2

使用JSoup解析URL

解析URL的方法跟解析字符串有點(diǎn)不一樣,但基本原理是相同的:

public class JSoupExample {

    public static void main(String[] args) throws IOException {

        Document doc = Jsoup.connect("https://www.wikipedia.org").get();

        Elements titles = doc.getElementsByClass("other-project");

            for (Element title : titles) {

                System.out.println(title.text());

        }

    }

}

要從URL抓取數(shù)據(jù),需要調(diào)用connect()方法,提供URL作為參數(shù)。然后使用get()從連接中獲取HTML。這個(gè)例子的輸出為:

Commons Freely usable photos & more

Wikivoyage Free travel guide

Wiktionary Free dictionary

Wikibooks Free textbooks

Wikinews Free news source

Wikidata Free knowledge base

Wikiversity Free course materials

Wikiquote Free quote compendium

MediaWiki Free & open wiki application

Wikisource Free library

Wikispecies Free species directory

Meta-Wiki Community coordination & documentation

可以看到,這個(gè)程序抓取了所有class為other-project的元素。

這種方法是最常用的,因此我們看一些通過(guò)URL進(jìn)行抓取的其他例子。

抓取指定URL的所有鏈接

 public void allLinksInUrl() throws IOException {

        Document doc = Jsoup.connect("https://www.wikipedia.org").get();

        Elements links = doc.select("a[href]");

        for (Element link : links) {

            System.out.println("\nlink : " + link.attr("href"));

            System.out.println("text : " + link.text());

        }

    }

運(yùn)行結(jié)果是一個(gè)很長(zhǎng)的列表:

Link : //en.wikipedia.org/

Text : English 5 678 000+ articles

Link : //ja.wikipedia.org/

Text : 日本語(yǔ) 1 112 000+ 記事

Link : //es.wikipedia.org/

Text : Espa?ol 1 430 000+ artículos

Link : //de.wikipedia.org/

Text : Deutsch 2 197 000+ Artikel

Link : //ru.wikipedia.org/

Text : Русский 1 482 000+ статей

Link : //it.wikipedia.org/

Text : Italiano 1 447 000+ voci

Link : //fr.wikipedia.org/

Text : Fran?ais 2 000 000+ articles

Link : //zh.wikipedia.org/

Text : 中文 1 013 000+ 條目

<!--A bunch of other languages -->
Text : Wiktionary Free dictionary

Link : //www.wikibooks.org/

Text : Wikibooks Free textbooks

Link : //www.wikinews.org/

Text : Wikinews Free news source

Link : //www.wikidata.org/

Text : Wikidata Free knowledge base

Link : //www.wikiversity.org/

Text : Wikiversity Free course materials

Link : //www.wikiquote.org/

Text : Wikiquote Free quote compendium

Link : //www.mediawiki.org/

Text : MediaWiki Free & open wiki application

Link : //www.wikisource.org/

Text : Wikisource Free library

Link : //species.wikimedia.org/

Text : Wikispecies Free species directory

Link : //meta.wikimedia.org/

Text : Meta-Wiki Community coordination & documentation

Link : https://creativecommons.org/licenses/by-sa/3.0/

Text : Creative Commons Attribution-ShareAlike License

Link : //meta.wikimedia.org/wiki/Terms_of_Use

Text : Terms of Use

Link : //meta.wikimedia.org/wiki/Privacy_policy

Text : Privacy Policy

與此相似,你還可以得到圖像的數(shù)量、元信息、表單參數(shù)等一切你能想到的東西,因此經(jīng)常被用于獲取統(tǒng)計(jì)數(shù)據(jù)。

使用JSoup解析文件

public void parseFile() throws URISyntaxException, IOException {

        URL path = ClassLoader.getSystemResource("page.html");

        File inputFile = new File(path.toURI());

        Document document = Jsoup.parse(inputFile, "UTF-8");

        System.out.println(document.title());

        //parse document in any way

    }

如果要解析文件,就不需要給網(wǎng)站發(fā)送請(qǐng)求,因此不用擔(dān)心運(yùn)行程序會(huì)給服務(wù)器增添太多負(fù)擔(dān)。盡管這種方法有許多限制,并且數(shù)據(jù)是靜態(tài)的,因而不適合許多任務(wù),但它提供了分析數(shù)據(jù)的更合法、更無(wú)害的方式。

得到的文檔可以用前面說(shuō)過(guò)的任何方式解析。

設(shè)置屬性值

除了讀取字符串、URL和文件并獲取數(shù)據(jù)之外,我們還能修改數(shù)據(jù)和輸入表單。

例如,在訪問(wèn)亞馬遜時(shí),點(diǎn)擊左上角的網(wǎng)站標(biāo)志,能返回到網(wǎng)站的首頁(yè)。

如果想改變這個(gè)行為,可以這樣做:

 public void setAttributes() throws IOException {

        Document doc = Jsoup.connect("https://www.amazon.com").get();
        Element element = doc.getElementById("nav-logo");

        System.out.println("Element: " + element.outerHtml());

        element.children().attr("href", "notamazon.org");

        System.out.println("Element with set attribute: " + element.outerHtml());

    }

獲取網(wǎng)站標(biāo)志的id后,我們可以查看其HTML。還可以訪問(wèn)它的子元素,并改變其屬性。

Element: <div id="nav-logo"> 

 <a href="/ref=nav_logo/135-9898877-2038645" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="/gp/prime/ref=nav_logo_prime_join/135-9898877-2038645" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>
Element with set attribute: <div id="nav-logo"> 

 <a href="notamazon.org" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="notamazon.org" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>

默認(rèn)情況下,兩個(gè)<a>子元素都指向了各自的鏈接。將屬性改變?yōu)閯e的值之后,可以看到子元素的href屬性被更新了。

添加或刪除類

除了設(shè)置屬性值之外,我們還可以修改前面的例子,給元素添加或刪除類:

public void changePage() throws IOException {

        Document doc = Jsoup.connect("https://www.amazon.com").get();

        Element element = doc.getElementById("nav-logo");

        System.out.println("Original Element: " + element.outerHtml());

        <!--Setting attributes -->

        element.children().attr("href", "notamazon.org");

        System.out.println("Element with set attribute: " + element.outerHtml());

        <!--Adding classes -->

        element.addClass("someClass");

        System.out.println("Element with added class: " + element.outerHtml());

        <!--Removing classes -->

        element.removeClass("someClass");

        System.out.println("Element with removed class: " + element.outerHtml());

    }

運(yùn)行代碼會(huì)給我們以下信息:

Original Element: <div id="nav-logo"> 

 <a href="/ref=nav_logo/135-1285661-0204513" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="/gp/prime/ref=nav_logo_prime_join/135-1285661-0204513" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>
Element with set attribute: <div id="nav-logo"> 

 <a href="notamazon.org" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="notamazon.org" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>
Element with added class: <div id="nav-logo" class="someClass"> 

 <a href="notamazon.org" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="notamazon.org" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>
Element with removed class: <div id="nav-logo"> 

 <a href="notamazon.org" class="nav-logo-link" tabindex="6"> <span class="nav-logo-base nav-sprite">Amazon</span> <span class="nav-logo-ext nav-sprite"></span> <span class="nav-logo-locale nav-sprite"></span> </a> 

 <a href="notamazon.org" aria-label="" tabindex="7" class="nav-logo-tagline nav-sprite nav-prime-try"> Try Prime </a> 

</div>

可以把新的代碼以.html形式保存到本機(jī),或者通過(guò)HTTP請(qǐng)求發(fā)送大歐網(wǎng)站上,不過(guò)要注意后者可能是非法的。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Web抓取框架JSoup怎么用”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI