通过电子表格导入 JSOUP 的 URL 以进行抓取

问题描述 投票:0回答:1

我终于让 IntelliJ 开始工作了。我正在使用下面的代码。它工作完美。我需要它一遍又一遍地循环,并从电子表格中提取链接,以便一遍又一遍地查找不同商品的价格。我有一个电子表格,其中从第 2 行开始的 C 列中包含一些示例 URL。如何让 JSOUP 使用此电子表格中的 URL,然后输出到 D 列?

public class Scraper {

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

    final Document document = Jsoup.connect("examplesite.com").get();

    for (Element row : document.select("#price")) {

        final String price = row.select("#price").text();

        System.out.println(price);
    }
}

预先感谢您的帮助! 艾瑞克

java excel web-scraping web-crawler jsoup
1个回答
0
投票

您可以使用 JExcel 库来读取和编辑工作表:https://sourceforge.net/projects/jexcelapi/ .

当您下载带有库的 zip 文件时,它也非常有用

tutorial.html

评论中的解释:

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class StackoverflowQuestion51577491 {

    private static final int URL_COLUMN = 2; // Column C
    private static final int PRICE_COLUMN = 3; // Column D

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

        // open worksheet with URLs
        Workbook originalWorkbook = Workbook.getWorkbook(new File("O:/original.xls"));
        // create editable copy
        WritableWorkbook workbook = Workbook.createWorkbook(new File("O:/updated.xls"), originalWorkbook);
        // close read-only workbook as it's not needed anymore
        originalWorkbook.close();
        // get first available sheet
        WritableSheet sheet = workbook.getSheet(0);
        // skip title row 0
        int currentRow = 1;
        Cell cell;
        // iterate each cell from column C until we find an empty one
        while (!(cell = sheet.getCell(URL_COLUMN, currentRow)).getType().equals(CellType.EMPTY)) {
            // raed cell contents
            String url = cell.getContents();
            System.out.println("parsing URL: " + url);
            // parse and get the price
            String price = parseUrlWithJsoupAndGetProductPrice(url);
            System.out.println("found price: " + price);
            // create new cell with price
            Label cellWithPrice = new Label(PRICE_COLUMN, currentRow, price);
            sheet.addCell(cellWithPrice);
            // go to next row
            currentRow++;
        }
        // save and close file
        workbook.write();
        workbook.close();
    }

    private static String parseUrlWithJsoupAndGetProductPrice(String url) throws IOException {
        // download page and parse it to Document
        Document doc = Jsoup.connect(url).get();
        // get the price from html
        return doc.select("#priceblock_ourprice").text();
    }
}

之前: enter image description here 后: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.