【问题标题】:How to scrape table data from specific site JSOUP如何从特定站点 JSOUP 中抓取表数据
【发布时间】:2020-03-19 10:36:38
【问题描述】:

我正在尝试从该站点的表格中抓取一些数据:https://www.worldometers.info/coronavirus/

这里是我试过的scraper源码

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

    String url = "https://www.worldometers.info/coronavirus/";
    try{
        Document doc = Jsoup.connect(url).get();
        Element table = doc.getElementById("main_table_countries_today");
        Elements rows = table.getElementsByTag("tr");

        for(Element row : rows){
            Elements tds = row.getElementsByTag("td");

            for(int i = 0;i<tds.size();i++){
                System.out.println(tds.get(i).text());
            }
        }

    }catch (IOException e){
        e.printStackTrace();
    }
}

这是输出 中国 80,928 +34 3,245 +8 70,420 7,263 2,274 56 意大利 35,713 ....

我只想抓取一个特定国家/地区的数据,例如。法国。 但我不知道该怎么做。

【问题讨论】:

  • 网站是如何组织的?如果您使用浏览器访问,您可以选择特定国家吗?一旦你可以手动完成,自动化应该不难。另一方面,如果您只想抓取可用数据的子集,那么编写代码以忽略您不想要的数据应该很简单,但需要了解网站的 HTML 是如何组织的。告诉我们你有什么以及它是怎么错的。
  • @tripleee 是的,我可以选择一些国家,比如中国,它会打开一个页面,我可以使用 getElementsByClass 选项轻松地从 div 中抓取数据。这仅适用于中国和其他少数国家。如果我想为阿尔及利亚抓取数据我必须通过抓取表格来做到这一点,这就是我被卡住的地方。在表格里面有一个带有“偶数”或“奇数”类的 tr,它包含更多保存数据的 td。
  • 关于 Stack Overflow 的适当问题将显示一些示例数据和您已经尝试过的内容的概述。我不是 Java 人,但你所描述的内容应该是简单明了的任何半体面的 HTML 解析器。

标签: java jsoup screen-scraping


【解决方案1】:

您必须先询问每个“td”是否包含“France”,然后才能打印该行。

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

    String url = "https://www.worldometers.info/coronavirus/";
    try{
        Document doc = Jsoup.connect(url).get();
        Element table = doc.getElementById("main_table_countries_today");
        Elements rows = table.getElementsByTag("tr");

        for(Element row : rows){

            Elements tds = row.getElementsByTag("td");
            for(int i = 0;i<tds.size();i++){
                if(tds.get(i).text().equals("France")){
                    System.out.println(row.text());
                }

            }
        }

    }catch (IOException e){
        e.printStackTrace();
    }

输出:

France 14,459 562 1,587 12,310 1,525 222

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2014-07-21
    • 2018-01-27
    相关资源
    最近更新 更多