gpt4 book ai didi

Java 加载网页并跟踪 HTML 中的变化

转载 作者:行者123 更新时间:2023-11-27 23:39:13 24 4
gpt4 key购买 nike

我正在尝试加载网页 http://www.twitch.tv/NAME_OF_CHANNEL/chat?opentga=1 以通过网络抓取跟踪 twitch 聊天。唯一的问题是,每当有人在聊天中键入消息时,ul 项就会添加到 html 代码中。我的问题是,如果我使用 Selenium 或仅使用 HTTP GET 请求加载页面,我如何才能继续获取更新的代码,以便我可以查看发送到聊天中的所有新聊天消息?

这是一些代码的样子。

enter image description here

如您所见,有一个 ul 元素,其中包含大量带有随机 ID 的 div 元素。在每个 div 元素中都有单独的聊天消息,其中包含特定信息,例如用户发送的内容和发送时间。 div 元素不断更新,每次发送消息时都会添加一个元素。每次发送消息时,如何跟踪所有 div 元素并将每个元素保存在列表中?谢谢!

最佳答案

您可以轮询您特定情况下的 DOM。polling 的含义是将驱动程序设置为监视状态,等待某些条件得到满足。您可以使用 implicitexplicit 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com