我正在尝试加载网页http://www.twitch.tv/NAME_OF_CHANNEL/chat?opentga=1
,以通过网络抓取来跟踪 twitch 聊天。唯一的问题是,每当有人在聊天中输入消息时,ul
项就会添加到 html 代码中。我的问题是,如果我使用 Selenium 或仅使用 HTTP GET 请求加载页面,我如何才能不断获取更新的代码,以便我可以查找发送到聊天中的所有新聊天消息?
这就是一些代码的样子。
正如您所看到的,有一个 ul
元素,其中包含大量具有随机 ID 的 div
元素。每个 div
元素中都有单独的聊天消息,其中包含某些信息,例如用户发送的内容和时间。 div
元素不断更新,每次发送消息时都会添加一个元素。如何跟踪每次发送消息时将每个元素保存在列表中的所有 div
元素?谢谢!
最佳答案
您可以轮询
您特定情况的 DOM。
轮询的含义是将驱动程序设置为监视状态,等待满足某些条件。
您可以使用隐式
或显式
waiting 。
这样的事情将是一个很好的开始
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
条评论。
选择器可能不正确。请随意更改它们。这是一个永无止境的轮询循环,因此您可能需要在此处引入某种退出逻辑。
关于Java 加载网页并跟踪 HTML 中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444150/