繁体   English   中英

如何在 Java Selenium 中刮取选定的表列并将它们写入 CVS

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

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

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++;          
            } 

抓取:通常当我想收集列表元素时,我会用 Xpath 代替 CssSelector 来 select。 如何通过 Xpath 访问元素的结构通常更清晰,并且取决于指定元素的一两个 integer 值。

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

第一个名字,'Airi Satou' 位于以下 Xpath: //*[@id="example"]/tbody/tr[1]/td[1]

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

您可以看到跨行 Xpath 的每条信息在“td”标记上有所不同。

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

并且发现安吉拉的position: //*[@id="example"]/tbody/tr[2]/td[2]

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

通过迭代 'tr' 和 'td' 的值,您可以获得整个表格。

至于写入 CSV,有一些可靠的 Java 库用于写入 CSV。 我认为这里有一个简单的示例: Java - 将字符串写入 CSV 文件

更新: @User169 看起来您正在为表中的每一行收集元素列表。 您希望逐一收集 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 + "]");
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM