Java using htmlunit analog login Crawl Sina microblog page

Source: Internet
Author: User
Import java.io.IOException;
Import java.net.MalformedURLException;
Import com.gargoylesoftware.htmlunit.BrowserVersion;
Import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
Import Com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
Import com.gargoylesoftware.htmlunit.WebClient;
Import Com.gargoylesoftware.htmlunit.html.HtmlInput;
Import Com.gargoylesoftware.htmlunit.html.HtmlPage;


public class Sinalogintest {
public static void Main (string[] args) throws Failinghttpstatuscodeexception, Malformedurlexception, IOException, interruptedexception {
WebClient client = new WebClient (browserversion.firefox_24);
Client.getoptions (). Setjavascriptenabled (True); The default execution of JS, if you do not perform JS, you may fail to login, because the user name Password box requires JS to draw.
Client.getoptions (). setcssenabled (false);
Client.setajaxcontroller (New Nicelyresynchronizingajaxcontroller ());
Client.getoptions (). Setthrowexceptiononscripterror (false);

HtmlPage page = Client.getpage ("Http://login.sina.com.cn/sso/login.php?client=ssologin.js (v1.3.16)");
System.out.println (Page.astext ());

Login
Htmlinput ln = Page.gethtmlelementbyid ("username");
Htmlinput pwd = Page.gethtmlelementbyid ("password");
Htmlinput btn = Page.getfirstbyxpath (".//*[@id = ' vform ']/div[3]/ul/li[6]/div[2]/input ');

Ln.setattribute ("Value", "Change here to your username");
Pwd.setattribute ("Value", "Change here to your password");

HtmlPage Page2 = Btn.click ();
Login is complete and you can now crawl any page you want.
System.out.println ("\n\n\n");
System.out.println (Page2.astext ());

HtmlPage Page3 = client.getpage ("http://weibo.com/friends?leftnav=1&wvr=5&isfriends=1&step=2");
System.out.println (":" + page3.asxml ());

Client.closeallwindows ();
}

}

< note > Retrieve HTML (for Page3, Page3.asxml ()) just use the positive to get what you want.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.