【问题标题】:Write data to Excel file将数据写入 Excel 文件
【发布时间】:2020-08-08 06:17:52
【问题描述】:

我已经尝试了以下代码,这些代码将 Excel 读取文件数据复制到 Excel 写入数据文件,但我希望 Web 元素到 Excel 写入数据文件。希望使用 Selenium Java 将每个 trtd 数据转换为 Excel 文件。在同一个类中读取 excel 文件并希望将 web 元素数据写入 Excel 文件。

public class NewTest {
    public static String driverPath = "D:/Testing/Drivers/";
    public static WebDriver driver;
    public static void main(String[] args) throws IOException{
        System.out.println("launching chrome browser");
        System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
        driver = new ChromeDriver();
        driver.navigate().to("anyurl");
        WebElement id = driver.findElement(By.xpath("//input[@id='txt_username']"));
        id.sendKeys("anyusername");
        WebElement pass = driver.findElement(By.xpath("//input[@id='txt_password']"));
        pass.sendKeys("anypass");
        driver.findElement(By.id("txtCaptcha")).click();
        WebDriverWait wait = new WebDriverWait(driver,100);
        new WebDriverWait(driver,100).until(ExpectedConditions.urlToBe("anyurl"));
        driver.findElement(By.linkText("Exit")).click();
        driver.get("anyurl");
                FileInputStream fs = new FileInputStream("D:\\Test.xls"); //or xlsx
                XSSFWorkbook workbook = new XSSFWorkbook(fs);
                XSSFSheet sheet = workbook.getSheetAt(0);
                Row row = sheet.getRow(0);
                Cell cell = row.getCell(0);    
driver.findElement(By.xpath("//form[@id=\'aspnetForm\']/div[3]/div/div/table/tbody/tr/td/div/input")).clear();
driver.findElement(By.xpath("//form[@id=\'aspnetForm\']/div[3]/div/div/table/tbody/tr/td/div/input")).sendKeys(sheet.getRow(0).getCell(0).getStringCellValue());
driver.findElement(By.xpath("//form[@id=\'aspnetForm\']/div[3]/div/div/table/tbody/tr/td/div/input[2]")).clear();
driver.findElement(By.xpath("//form[@id=\'aspnetForm\']/div[3]/div/div/table/tbody/tr/td/div/input[2]")).sendKeys(sheet.getRow(0).getCell(1).getStringCellValue());
driver.findElement(By.xpath("//input[@id=\'ctl00_ContentPlaceHolder1_btn_submit\']")).click();
WebElement element = driver.findElement(By.xpath("//*tr[@id='ctl00_ContentPlaceHolder1_tr_data']/td/div/table/tbody"));
                List<WebElement> tbdy = element.findElements(By.tagName("tbody"));
                List<WebElement> tr = tbdy.get(0).findElements(By.tagName("tr"));
            try {
                    String filename = "D:\\Test.xls";
                    HSSFWorkbook workbook = new HSSFWorkbook();
                    HSSFSheet sheet = workbook.createSheet("FirstSheet");
                    CellStyle style = workbook.createCellStyle();//Create style
                    HSSFRow row = sheet.createRow(0);
                     }
                    for (int i = 0; i < tr.size(); i++) {
                        HSSFRow row2 = sheet.createRow(i+1);
                        List<WebElement> td = tr.get(i).findElements(By.tagName("td"));
                        for (int j = 0; j < td.size(); j++) {
                            td.get(j).getText();
                        row2.createCell(j).setCellValue(td.get(j).getText());
                        }
                    }
                    FileOutputStream fileOut = new FileOutputStream(filename);
                    workbook.write(fileOut);
                    fileOut.close();
                    System.out.println("Your excel file has been generated!");
}
     }```

【问题讨论】:

  • 在任何人可以帮助您解决此问题之前,您需要稍微清理一下问题。目前尚不清楚您要说什么。请尽量使用完整的思想和句子。技术问题很难回答,当我们无法正确理解您的问题时,就无法回答。

标签: selenium selenium-webdriver apache-poi


【解决方案1】:

很难说你在做什么,但这里有一个通用的例子,可以帮助你朝着正确的方向前进。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions() 
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\\Utility\\chromedriver.exe')
driver.get("http://www.ultimatetennisstatistics.com/playerProfile?playerId=4742")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@id='playerPills']//a[@class='dropdown-toggle'][normalize-space()='Statistics']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='dropdown-menu']//a[@id='statisticsPill'][normalize-space()='Statistics']"))).click()
statistics_items = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.XPATH, "//table[@class='table table-condensed table-hover table-striped']//tbody//tr/td")))
statistics_value = WebDriverWait(driver, 10).until(EC.visibility_of_any_elements_located((By.XPATH, "//table[@class='table table-condensed table-hover table-striped']//tbody//tr//following::th[1]")))
for item, value in zip(statistics_items, statistics_value):
    print('{} {}'.format(item.text, value.text))

结果:

Ace % 4.0%
Double Fault % 2.1%
1st Serve % 68.7%
1st Serve Won % 71.8%
2nd Serve Won % 57.3%
Break Points Saved % 66.3%
Service Points Won % 67.2%
Service Games Won % 85.6%

现在,不再打印结果,而是将所有内容发送到数据框并将数据框保存到 Excel。

df.to_excel("output.xlsx")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2011-03-09
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多