沒有調用新浪的API,在程序中加入本身的賬號和密碼就能發送微博,代碼徹底在後臺運行,不用打開瀏覽器。web
用了HtmlUnit這個庫來模擬登陸還有發送微博。瀏覽器
先上效果圖:ui
這個是剛登錄上獲取第一頁的信息。spa
發送微博:code
沒什麼難的地方,找到相應的按鈕和文本域,而後點擊,簡單說就是用代碼模仿用戶的操做。orm
public class weibo { public static void main(String args[]) throws FailingHttpStatusCodeException, MalformedURLException, IOException, InterruptedException{ //新浪微博登陸頁面 String baseUrl = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F"; //打開 WebClient webClient = new WebClient(BrowserVersion.CHROME); webClient.addRequestHeader("User-Agent", "Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53"); //webClient.addRequestHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.122 Mobile Safari/537.36"); HtmlPage page = webClient.getPage(baseUrl); //等待頁面加載 Thread.sleep(1000); //獲取輸入賬號的控件 HtmlInput usr = (HtmlInput) page.getElementById("loginName"); usr.setValueAttribute("Your Account"); //獲取輸入密碼的控件 HtmlInput pwd = (HtmlInput) page.getElementById("loginPassword"); pwd.setValueAttribute("Your Password"); //點擊登陸 DomElement button = page.getElementById("loginAction"); page =(HtmlPage) button.click(); //等待頁面加載 Thread.sleep(1000); //獲取到「寫微博」這個按鈕,由於這個按鈕沒有name和id,獲取全部<a>標籤 DomNodeList<DomElement> button2 = page.getElementsByTagName("a"); //跳轉到發送微博頁面 page =(HtmlPage)button2.get(4).click(); //等待頁面加載 Thread.sleep(1000); //獲取發送控件 標籤爲<a>中的2個 DomNodeList<DomElement> button3 = page.getElementsByTagName("a"); //獲取文本宇 HtmlTextArea content =(HtmlTextArea) page.getElementById("txt-publisher"); DomElement fasong = button3.get(1); content.focus(); Date date = new Date(); //填寫你要發送的內容 content.setText("使用JAVA發送微博!!!!\n"+date); //改變發送按鈕的屬性,不能沒法發送 fasong.setAttribute("class", "fr txt-link"); //發送!!! page = (HtmlPage)fasong.click(); Thread.sleep(5000); System.out.println(page.asText()); } }
好啦,就是這麼簡單!blog