【问题标题】:Java Load Web Page and Keep Track of Changes in HTMLJava 加载网页并跟踪 HTML 中的更改
【发布时间】:2015-09-07 18:14:42
【问题描述】:

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

这就是一些代码的样子。

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

【问题讨论】:

    标签: java html selenium


    【解决方案1】:

    您可以poll 特定案例的 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());
        }
    }
    

    这可以清理。可能有错误,但逻辑很简单。

    您等到拥有 cmets 的容器。然后你找到当时所有的 cmets 并得到他们的号码。之后,您只需等到“看到”initial_number_of_comments + 1 评论。

    选择器可能不正确。随意更改它们。这是一个永无止境的轮询循环,因此您可能需要在此处引入某种退出逻辑。

    【讨论】:

    • 谢谢,我认为这对我正在做的事情有用! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多