如何使用 Selenium 和 Java 加载和收集所有评论

How to load and collect all comments with Selenium and Java

我有 Java 应用程序正在使用 Selenium Web Driver 从 Google Play Store 应用程序获取 crawl/scrape 信息。我有大约 30 个来自应用程序的链接,但我无法从每个应用程序收集 ALL 评论。 例如 this 应用程序需要大量滚动才能加载所有评论,但其他一些应用程序需要 less/more 滚动。 我如何动态加载每个应用程序的所有评论?

由于您没有共享示例代码,我将共享 javascript 片段,然后提供一个 C# 实现,您可以在您的 Java Selenium 项目中使用它。

示例Java脚本代码

let i=0;
var element = document.querySelectorAll("div>span[jsname='bN97Pc']")[i];
var timer = setInterval(function()
{
    console.log(element);
    element.scrollIntoView();

        i++;
        element = document.querySelectorAll("div>span[jsname='bN97Pc']")[i];
        if(element===undefined)
            clearTimeout(timer);

},500);

运行 上面的代码在控制台上,一旦您进入带有您共享的评论的应用程序页面,将滚动到页面末尾,同时在控制台上打印出每条评论。

带有 Selenium C# 绑定的示例代码:

static void Main(string[] args)
        {
            ChromeDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://play.google.com/store/apps/details?id=com.plokia.ClassUp&hl=en&showAllReviews=true");

            ExtractComments(driver);
            driver.Quit();
        }

        private static void ExtractComments(ChromeDriver driver,int startingIndex=0)
        {
            IEnumerable<IWebElement> comments = driver.FindElementsByCssSelector(@"div>span[jsname='bN97Pc']");

            if (comments.Count() <= startingIndex)
                return; //no more new comments hence return.

            if (startingIndex > 0)
                comments = comments.Skip(startingIndex); //skip already processed elements


            //process located comments
            foreach (var comment in comments)
            {
                string commentText = comment.Text;
                Console.WriteLine(commentText);
                (driver as IJavaScriptExecutor).ExecuteScript("arguments[0].scrollIntoView()", comment);
                Thread.Sleep(250);
                startingIndex++;
            }

            Thread.Sleep(2000); // Let more comments load once we have consumed existing
            ExtractComments(driver,startingIndex); //Recursively call self to process any further comments that have been loaded after scrolling
        }

希望对您有所帮助。