2015-09-07 32 views
2

我試圖加載網頁http://www.twitch.tv/NAME_OF_CHANNEL/chat?opentga=1以跟蹤通過網絡抓取進行的抽搐聊天。唯一的問題是,無論什麼時候有人在聊天中輸入消息,ul項目都會添加到html代碼中。我的問題是,如果我使用Selenium或HTTP GET請求加載頁面,如何獲取更新後的代碼,以便查找發送到聊天中的所有新聊天消息?Java加載網頁並保留HTML中的更改跟蹤

這是一些代碼的樣子。

enter image description here

正如你可以看到有是有一個巨大的隨機IDS div元素的列表中ul元素。在每個div元素中都有單獨的聊天消息,並具有某些信息,例如用戶在什麼時間發送的。 div元素是不斷更新的內容,每次發送消息時都會添加一個元素。每次發送消息時,如何跟蹤所有div元素將每個元素保存在列表中?謝謝!

回答

2

您可以poll您的具體情況的DOM。 polling的含義是將驅動程序設置爲監視器狀態,等待某種條件得以滿足。 您可以有implicitexplicitwaiting

像這樣的事情會是一個很好的開端

public static void main(String[] args) throws Exception { 
    WebDriver driver = new FirefoxDriver(); 
    driver.get("http://www.twitch.tv/NAME_OF_CHANNEL/chat?opentga=1"); 

    WebDriverWait initialWait = new WebDriverWait(driver, 60); 
    WebElement commentsContainer = initialWait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("ul.chat-lines"))); 
    if(commentsContainer == null) 
     throw new Exception("Page unresponsive!!!"); 

    int numberOfComments = commentsContainer.findElements(By.cssSelector("div[id^=ember]")).size() + 1; 
    while(true) { 
     String newCommentSelector = "chat-lines > div:nth-child(" + numberOfComments + ")"; 
     WebElement newComment = (new WebDriverWait(driver, 60)) 
      .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(newCommentSelector))); 
     if(newComment == null) continue; 

     numberOfComments++; 

     System.out.println(newComment.getText()); 
    } 
} 

這可以被清理。可能有錯誤,但邏輯很直接。

你等到你有評論的容器。然後你會發現所有評論,並獲得他們的電話號碼。之後,您只需等到「看到」initial_number_of_comments + 1評論。

選擇器可能不正確。隨意隨意改變他們。這是一個永無止境的輪詢循環,所以你可能想在這裏介紹一些退出邏輯。

+0

謝謝,我認爲這將適用於我正在做的事! :d –