资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Web抓取框架JSoup怎么用-创新互联

这篇文章主要介绍了Web抓取框架JSoup怎么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

成都创新互联公司专注于武鸣企业网站建设,响应式网站,商城网站制作。武鸣网站建设公司,为武鸣等地区提供建站服务。全流程定制开发,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务

仅供参考学习。

Web抓取框架

就像许多现代科技一样,从网站提取信息这一功能也有多个框架可以选择。最流行的有JSoup、HTMLUnit和Selenium WebDriver。这篇文章讨论JSoup。

JSoup

JSoup是个开源项目,提供强大的数据提取API。可以用它来解析给定URL、文件或字符串中的HTML。它还能操纵HTML元素和属性。

使用JSoup解析字符串

解析字符串是JSoup的最简单的使用方式。

public class JSoupExample {

    public static void main(String[] args) {

        String html = "Website title

Sample paragraph number 1 

Sample paragraph number 2

";
        Document doc = Jsoup.parse(html);

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

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

        for (Element paragraph : paragraphs) {

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

        }

    }

这段代码非常直观。调用parse()方法可以解析输入的HTML,将其变成Document对象。调用该对象的方法就能操纵并提取数据。

在上面的例子中,我们首先输出页面的标题。然后,我们获取所有带有标签“p”的元素。然后我们依次输出每个段落的文本。

运行这段代码,我们可以得到以下输出:

Website title

Sample paragraph number 1

Sample paragraph number 2

使用JSoup解析URL

解析URL的方法跟解析字符串有点不一样,但基本原理是相同的:

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抓取数据,需要调用connect()方法,提供URL作为参数。然后使用get()从连接中获取HTML。这个例子的输出为:

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

可以看到,这个程序抓取了所有class为other-project的元素。

这种方法是最常用的,因此我们看一些通过URL进行抓取的其他例子。

抓取指定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());

        }

    }

运行结果是一个很长的列表:

Link : //en.wikipedia.org/

Text : English 5 678 000+ articles

Link : //ja.wikipedia.org/

Text : 日本語 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+ 條目


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

与此相似,你还可以得到图像的数量、元信息、表单参数等一切你能想到的东西,因此经常被用于获取统计数据。

使用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

    }

如果要解析文件,就不需要给网站发送请求,因此不用担心运行程序会给服务器增添太多负担。尽管这种方法有许多限制,并且数据是静态的,因而不适合许多任务,但它提供了分析数据的更合法、更无害的方式。

得到的文档可以用前面说过的任何方式解析。

设置属性值

除了读取字符串、URL和文件并获取数据之外,我们还能修改数据和输入表单。

例如,在访问亚马逊时,点击左上角的网站标志,能返回到网站的首页。

如果想改变这个行为,可以这样做:

 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());

    }

获取网站标志的id后,我们可以查看其HTML。还可以访问它的子元素,并改变其属性。

Element:  

  Amazon    

  Try Prime  


Element with set attribute:  

  Amazon    

  Try Prime  


默认情况下,两个子元素都指向了各自的链接。将属性改变为别的值之后,可以看到子元素的href属性被更新了。

添加或删除类

除了设置属性值之外,我们还可以修改前面的例子,给元素添加或删除类:

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());

        

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

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

        

        element.addClass("someClass");

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

        

        element.removeClass("someClass");

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

    }

运行代码会给我们以下信息:

Original Element:  

  Amazon   
 

  Try Prime  


Element with set attribute:  

  Amazon    

  Try Prime  


Element with added class:  

  Amazon    

  Try Prime  


Element with removed class:  

  Amazon    

  Try Prime  


可以把新的代码以.html形式保存到本机,或者通过HTTP请求发送大欧网站上,不过要注意后者可能是非法的。

感谢你能够认真阅读完这篇文章,希望小编分享的“Web抓取框架JSoup怎么用”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联-成都网站建设公司行业资讯频道,更多相关知识等着你来学习!


文章标题:Web抓取框架JSoup怎么用-创新互联
URL网址:http://cdkjz.cn/article/jsjjh.html
返回首页 了解更多建站资讯
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220