java做web抓取

时间:2023-03-10 04:10:15
java做web抓取

就像许多现代科技一样,从网站提取信息这一功能也有多个框架可以选择。最流行的有JSoup、HTMLUnit和Selenium WebDriver。我们这篇文章讨论JSoup。JSoup是个开源项目,提供强大的数据提取API。可以用它来解析给定URL、文件或字符串中的HTML。它还能操纵HTML元素和属性。

        <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.</version>
</dependency>
 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());

        }

调用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的元素。

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

        }

    }

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

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

    }

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

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