Jsoup登入解析網頁資訊

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

今天解析網頁的時候,遇到必須登入後才能夠訪問的問題,在網上搜尋了一些資料,反正有人做出來了,不過是使用HttpClient+Jsoup來實現的,我不清楚他們使用什麼版本的Jsoup,地址:

HttpClient類比登陸人人網,並且爬取日誌內容(一),http://bbs.csdn.net/topics/390269063,查看現在的Jsoup API,可以直接類比登陸,擷取伺服器返回的資訊。

我這裡是使用水木社區做Demo,其中下面的id和passwd分別是提交form表單中使用者名稱和密碼的input的name

<form action="/user/login" method="post"><ul class="sec"><li>使用者名稱:<br/><input type="text" name="id" /></li><li>密碼:<br/><input type="password" name="passwd" /></li><li><input type="checkbox" name="save" />記住我<br/><input type="submit" class="btn" value="登入" /></li></ul></form>

Map<String, String> map = new HashMap<String, String>();map.put("id", "****");map.put("passwd", "****");Response response = Jsoup.connect("http://m.newsmth.net/user/login").data(map).method(Method.POST).timeout(20000).execute();if (response.statusCode() == 200) {SmthApp.getInstance().setCookies(response.cookies());}

其中Response裡面就有我們需要的Cookie,擷取的方式為response.cookies()傳回型別是Map,下面是擷取瀏覽器登入返回的Cookie內容,同樣我們擷取的Cookies也是這些內容。

Set-Cookie:main[UTMPUSERID]=***; path=/; domain=.newsmth.netSet-Cookie:main[UTMPKEY]=97311264; path=/; domain=.newsmth.netSet-Cookie:main[UTMPUSERID]=guest; path=/; domain=.newsmth.netSet-Cookie:main[PASSWORD]=%2501g2VSVO%257D%2507%251DW%253B%2524K%2B%251C%2500a%2502%2501%257DF%2505X; path=/; domain=.newsmth.netSet-Cookie:main[UTMPNUM]=9967; path=/; domain=.newsmth.netSet-Cookie:main[UTMPKEY]=68252570; path=/; domain=.newsmth.netSet-Cookie:main[UTMPNUM]=37535; path=/; domain=.newsmth.net
當解析需要登陸的頁面時,
Document document = Jsoup.connect(url).timeout(20000).cookies(SmthApp.getInstance().getCookies())//這個就是上面擷取的cookies.get();
這樣就可以類比登陸解析頁面,需要注意的是這個是有時間限制的,當失效後再次請求擷取最新的Cookie。


聯繫我們

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