如何抓取选定的 table 列并将它们写入 Java Selenium 中的 CVS

How to scrape selected table columns and write them in CVS in Java Selenium

我的目标是使用 Java Selenium 抓取 数据。我能够加载 selenium 驱动程序,连接到网站并获取第一列,然后转到下一个分页按钮,直到它变为禁用并将其写入控制台。这是我到目前为止所做的:

public static WebDriver driver;

 public static void main(String[] args) throws Exception {

  System.setProperty("webdriver.chrome.driver", "E:\eclipse-workspace\package-name\src\working\selenium\driver\chromedriver.exe");
  System.setProperty("webdriver.chrome.silentOutput", "true");

  driver = new ChromeDriver();
  driver.get("https://datatables.net/examples/basic_init/zero_configuration.html");
  driver.manage().window().maximize();
  compareDispalyedRowCountToActualRowCount();
 }

 public static void compareDispalyedRowCountToActualRowCount() throws Exception {

  try {
   Thread.sleep(5000);
   List<WebElement> namesElements = driver.findElements(By.cssSelector("#example>tbody>tr>td:nth-child(1)"));
   System.out.println("size of names elements : " + namesElements.size());

   List<String> names = new ArrayList<String>();
   //Adding column1 elements to the list
   for (WebElement nameEle : namesElements) {
    names.add(nameEle.getText());
   }
   //Displaying the list elements on console
   for (WebElement s : namesElements) {
    System.out.println(s.getText());
   }
   
   //locating next button
   String nextButtonClass = driver.findElement(By.id("example_next")).getAttribute("class");

   //traversing through the table until the last button and adding names to the list defined about
   while (!nextButtonClass.contains("disabled")) {
        driver.findElement(By.id("example_next")).click();
        Thread.sleep(1000);
        namesElements = driver.findElements(By.cssSelector("#example>tbody>tr>td:nth-child(1)"));
            for (WebElement nameEle : namesElements) {
             names.add(nameEle.getText());
            }
            nextButtonClass = driver.findElement(By.id("example_next")).getAttribute("class");
           }
       //printing the whole list elements
       for (String name : names) {
        System.out.println(name);
       }
   //counting the size of the list
   int actualCount = names.size();
   System.out.println("Total number of names :" + actualCount);

   //locating displayed count 
   String displayedCountString = driver.findElement(By.id("example_info")).getText().split(" ")[5];
   int displayedCount = Integer.parseInt(displayedCountString);

   System.out.println("Total Number of Displayed Names count:" + displayedCount);

   Thread.sleep(1000);

   // Actual count calculated Vs Dispalyed Count
   if (actualCount == displayedCount) {
    System.out.println("Actual row count = Displayed row Count");
   } else {
    System.out.println("Actual row count !=  Displayed row Count");
    throw new Exception("Actual row count !=  Displayed row Count");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

我想:

  1. 抓取 多列或可能被选中的列,例如在此LINK 姓名、办公室和年龄列
  2. 然后想把这些列数据写入CSV文件

更新
我试过这样但不是 运行:

for(WebElement trElement : tr_collection){
             int col_num=1;
             List<WebElement> td_collection = trElement.findElements(
                     By.xpath("//*[@id=\"example\"]/tbody/tr[rown_num]/td[col_num]")
                     );        
             
                for(WebElement tdElement : td_collection){
                   rows += tdElement.getText()+"\t";
                   col_num++;                     
                }   
             rows = rows + "\n";
             row_num++;          
            } 

抓取: 通常当我想收集列表元素时,我会 select 通过 Xpath 而不是 CssSelector。如何通过Xpath访问元素的结构通常比较清晰,取决于指定元素的一两个整数值。

因此对于您想要查找名称的示例,您将通过 Xpath 找到一个元素,即列表的 Xpath 中的下一个元素,然后找到不同的值:

名字 'Airi Satou' 在以下 Xpath 中找到: //*[@id="example"]/tbody/tr[1]/td[1]

Airi 的职位具有以下 Xpath: //*[@id="example"]/tbody/tr[1]/td[2]

您可以看到,每行信息的 Xpath 在 'td' 标记上都不同。

找到列表中的下一个名称 'Angela Ramos': //*[@id="example"]/tbody/tr[2]/td[1]

找到安吉拉的位置: //*[@id="example"]/tbody/tr[2]/td[2]

您可以看到列中的差异是由 'tr' 标记控制的。

通过遍历 'tr' 和 'td' 的值,您可以获得整个 table.

至于写入 CSV,有一些可靠的 Java 库可用于写入 CSV。我认为这里有一个简单的例子:

更新: @User169 看起来您正在为 table 中的每一行收集元素列表。您想要一个接一个地收集 Xpath,遍历您最初找到的 webElement 列表。试试这个,然后添加到它,这样它就会得到文本并将它保存到一个数组中。

for (int num_row = 1; num_row < total_rows; num_row++){
    for (int num_col = 1; num_col < total_col; num_col++){
        webElement info = driver.findElement(By.xpath("//*[@id=\"example\"]/tbody/tr[" + row_num + ']/td[' + col_num + "]");
    }
}

我还没有测试过,所以它可能需要一些小的改动。