java做web抓取

來源:互聯網
上載者:User

標籤:web   site   int   ict   guide   html   屬性   links   syntax   

就像許多現代科技一樣,從網站提取資訊這一功能也有多個架構可以選擇。最流行的有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.3</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 titleSample paragraph number 1Sample 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 & moreWikivoyage Free travel guideWiktionary Free dictionaryWikibooks Free textbooksWikinews Free news sourceWikidata Free knowledge baseWikiversity Free course materialsWikiquote Free quote compendiumMediaWiki Free & open wiki applicationWikisource Free libraryWikispecies Free species directoryMeta-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    }

如果要解析檔案,就不需要給網站發送請求,因此不用擔心運行程式會給伺服器增添太多負擔。儘管這種方法有許多限制,並且資料是靜態,因而不適合許多任務,但它提供了分析資料的更合法、更無害的方式。

得到的文檔可以用前面說過的任何方式解析。

java做web抓取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.