如何使用Selenium阅读youtube评论

How to read youtube comments using Selenium?

本文关键字:youtube 评论 阅读 Selenium 何使用      更新时间:2023-09-26

我正在尝试使用以下代码阅读youtube视频评论:

FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com/watch?v=JcbBNpYkuW4");
WebElement element = driver.findElementByCssSelector("#watch-discussion");
System.out.println(element.getText()); // this prints: loading..
// scrolll down so that comments start to load
driver.executeScript("window.scrollBy(0,500)", "");
Thread.sleep(10000);
element = driver.findElementByCssSelector("#watch-discussion");
System.out.println(element.getText());

最后一条语句输出一个空字符串。为什么?

这有点棘手,因为所有的注释都写在一个单独的iframe标签内的手表讨论。你必须首先使用driver.switchTo().frame("put ID或Name here")打开iframe;但是iframe id是一个随机值。切换到该iframe后,您可以找到注释,所有注释都在一个div中,类名为"Ct",因此您可以使用XPATH获取这些注释。请看下面的工作代码

FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.youtube.com/watch?v=JcbBNpYkuW4");
WebElement element = driver.findElementByCssSelector("#watch-discussion");
System.out.println(element.getText()); // this prints: loading..
// scrolll down so that comments start to load
driver.executeScript("window.scrollBy(0,500)", "");
Thread.sleep(20000);
List<WebElement> iframes = driver.findElements(By.xpath("//iframe"));
for(WebElement e : iframes) {       
    if(e.getAttribute("id") != null && e.getAttribute("id").startsWith("I0_")) {
    // switch to iframe which contains comments
    driver.switchTo().frame(e);
    break;
    }
}
// fetch all comments
List<WebElement> comments = driver.findElements(By.xpath("//div[@class='Ct']"));
for(WebElement e : comments) {      
    System.out.println(e.getText());
}

我建议您尝试这个API,它非常容易/可靠,而不是依赖于元素的x路径。此外,动态页面/内容也不能依赖Xpath。