簡體   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