提取松散结构的维基百科文本。 HTML

时间:2015-04-23 01:26:48

标签: html regex parsing jsoup wikipedia

维基百科消歧页面上的一些html,我们应该说是不明确的,即连接到名为Corzine的特定人的链接难以使用jsoup捕获,因为它们没有明确的结构,它们也不像this example那样生活在特定的部分。请参阅页面Corzine page here

我怎样才能掌握它们? jsoup是否适合执行此任务?

也许我应该使用正则表达式,但我担心这样做是因为我希望它可以推广。

</b> may refer to:</p> 
 <ul> 
  <li><a href

^这是标准的,也许我可以使用正则表达式来匹配它?

<p><b>Corzine</b> may refer to:</p> 
 <ul> 
  <li><a href="/wiki/Dave_Corzine" title="Dave Corzine">Dave Corzine</a> (born 1956), basketball player</li> 
  <li><a href="/wiki/Jon_Corzine" title="Jon Corzine">Jon Corzine</a> (born 1947), former CEO of <a href="/wiki/MF_Global" title="MF Global">MF Global</a>, former Governor on New Jersey, former CEO of <a href="/wiki/Goldman_Sachs" title="Goldman Sachs">Goldman Sachs</a></li> 
 </ul> 
 <table id="setindexbox" class="metadata plainlinks dmbox dmbox-setindex" style="" role="presentation"> 

理想的输出是

Dave Corzine
Jon Corzine

也许可以匹配</b> may refer to:</p>部分和<table id="setindexbox"部分并提取其中的所有内容。我想jsoup中<table id="setindexbox"可以很容易匹配,但</b> may refer to:</p>应该更加难以理解,因为<b><p>不是很明显。

我试过了:

      Elements table = docx.select("ul");
      Elements links = table.select("li");



    Pattern ppp = Pattern.compile("table id=\"setindexbox\" ");
    Matcher mmm = ppp.matcher(inputLine);

    Pattern pp = Pattern.compile("</b> may refer to:</p>");
    Matcher mm = pp.matcher(inputLine);
    if (mm.matches()) 
    {
    while(!mmm.matches())
      for (Element link: links) 
      {
          String url = link.attr("href");
          String text = link.text();
          System.out.println(text + ", " + url);
      }
    }

但它没有用。

1 个答案:

答案 0 :(得分:2)

此选择器有效:

Elements els = doc.select("p ~ ul a:eq(0)");

请参阅:http://try.jsoup.org/~yPvgR0pxvA3oWQSJte4Rfm-lS2Y

正在寻找a:eq(0)ul兄弟的第一个A元素pp:contains(corzine) ~ ul a:eq(0)。如果还有其他冲突,您也可以:contains(may refer to) ~ ul a:eq(0)

或者更一般地说:{{1}}

很难概括维基百科,因为它是非结构化的。但恕我直言,使用解析器和CSS选择器比使用正则表达式更容易,特别是在模板更改等时间。