【问题标题】:Extract a specific line from a webpage using JSoup for Java使用 JSoup for Java 从网页中提取特定行
【发布时间】:2013-01-21 21:22:52
【问题描述】:

您好,我想使用 JSoup 库从网站上抓取一些文本。我尝试了以下代码,这给了我整个网页,我只想提取一个特定的行。这是我正在使用的代码:

Document doc = null;
try {
doc = Jsoup.connect("http://www.example.com").get();
} catch (IOException e) {
e.printStackTrace();
}
String text = doc.html();

System.out.println(text);

打印出以下内容

<html>
 <head></head>
 <body>
  Martin,James,28,London,20k
  <br /> Sarah,Jackson,43,Glasgow,32k
  <br /> Alex,Cook,22,Liverpool,18k
  <br /> Jessica,Adams,34,London,27k
  <br /> 
 </body>
</html>

如何仅提取读取 Alex,Cook,22,Liverpool,18k 的第 6 行并将其放入数组中,其中每个元素都是逗号前的单词(例如:[0] = Alex,[1] = Cook 等)

【问题讨论】:

  • 你对目标网站有控制权吗?如果是这样,那么您是否可以更改 html 输出以更轻松地捕获此数据?
  • @Shane 很遗憾我无法控制网站

标签: java screen-scraping web-scraping jsoup


【解决方案1】:

也许您必须稍微格式化(?)结果:

    Document doc = Jsoup.connect("http://www.example.com").get();
    int count = 0; // Count Nodes

    for( Node n : doc.body().childNodes() )
    {
        if( n instanceof TextNode )
        {
            if( count == 2 ) // Node 'Alex'
            {
                String t[] = n.toString().split(","); // you have an array with each word as string now

                System.out.println(Arrays.toString(t)); // eg. output
            }
            count++;
        }
    }

输出:

[ Alex, Cook, 22, Liverpool, 18k ]

编辑:

由于您无法通过其内容选择TextNode(仅适用于Elements),您需要一个小解决方法:

for( Node n : doc.body().childNodes() )
{
    if( n instanceof TextNode )
    {
        str = n.toString().trim();

        if( str.toLowerCase().startsWith("alex") ) // Node 'Alex'
        {
            String t[] = n.toString().split(","); // you have an array with each word as string now

            System.out.println(Arrays.toString(t)); // eg. output
        }
    }
}

【讨论】:

  • 干杯,还有一件事,有时网站上的内容会略有变化,所以是否有可能得到以 Alex 开头的行而不是第 6 行?
  • 我添加了另一种解决方案(请参阅编辑) - 不是最优雅的解决方案,但它有效。
猜你喜欢
  • 2013-02-16
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多