首页 > 解决方案 > 当反应仅显示其中一部分时,如何使用硒获取整个表

问题描述

示例网站:

https://listen.tidal.com/view/pages/single-module-page/b4104df9-ee72-4c3d-a7b4-30fa61faf56d/5/889e7c2a-e3be-472b-9801-bf6b40655050/1?artistId=8992

我使用 css 来获取如下行:

div[role=row]

所以代码就像

dirver.findElementsByCss(div[role=row])

并且数字只是显示的,也就是可见的行数,而不是整行。如何制作一个可以占用所有行的脚本?

1)

我试过像这里一样缩小,失败:

2)

向下滚动似乎不是最理想的,也不是很不精确的方式来做这样的事情

我正在为 Crome 77 和 python 使用 ChromeDriver

标签: pythonseleniumselenium-webdriverselenium-chromedriver

解决方案


由于该表使用 React,因此这些元素甚至根本不存在于页面上,除非您向下滚动到它们。我知道您提到滚动不是最佳解决方案,但如果您需要表中的所有行,滚动是这里唯一的选择。

我已经实现了一个使用坐标向下滚动页面的示例 ScrollDown 方法。代码在 C# 中,但其他语言的想法是相同的。

要使用 Javascript 滚动,您需要提供要滚动到的坐标。如果您希望滚动多次——例如,向下滚动、获取表格行、继续向下滚动并获取表格行直到到达表格末尾——您将需要更新yCoordinate您正在滚动的内容。由于滚动是一个向上/向下的过程,因此您xCoordinate每次都可以使用相同的。

关于increment- 这个变量是指你想一次滚动多少。increment应该等于您希望滚动的像素数。如果要一次滚动 3 行,并且每行高 100 像素,则需要设置increment为 300。

由于我不知道您的页面大小或布局,因此无法为您提供更详细的方法。我建议实施此方法并尝试使用不同的 x/y 坐标进行滚动,以便为您的测试应用程序获得个性化的解决方案。

public void ScrollDown(int startX, int startY, int increment, int numberOfScrolls) 
{
    // cast webdriver to javascript executor
    var executor = ((IJavaScriptExecutor) driver);

    // keep track of current y coordinate
    // since we are scrolling down, y coordinate will change with each scroll
    var currentYCoordinate = startY;

    // scroll down in a loop
    for (int i = 0; i < numberOfScrolls; i++)
    {
        // scroll down
        executor.ExecuteScript("window.scrollTo({startX}, {currentYCoordinate});");

        // todo: implement any FindElement methods to get the new elements which have been scrolled into view.

        // update y coordinate since we just scrolled down
        currentYCoordinate = currentYCoordinate + increment;

     }
}

推荐阅读