简体   繁体   English

如何在Java中使用正则表达式模式从HTML页面提取数据

[英]How to Extract data from HTML page using regex pattern in java

I'm trying to extract data from an html page as to store them in a String array 我正在尝试从html页面提取数据以将其存储在String数组中

In the HTML page values are shown like this 在HTML页面中,值显示如下:

 <tbody>
                      <tr>
                        <td style="width: 14%;">88055</td>
                        <td style="width: 19%;" class="gris">Ville</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/88055/" >Amos</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/880/" >Abitibi</a></td>
                      </tr>
                      <tr>
                        <td style="width: 14%;">85080</td>
                        <td style="width: 19%;" class="gris">Village</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/85080/" >Angliers</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/850/" >Témiscamingue</a></td>
                      </tr>
                      <tr>
                        <td style="width: 14%;">87050</td>
                        <td style="width: 19%;" class="gris">Municipalité</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/87050/" >Authier</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/870/" >Abitibi-Ouest</a></td>
                      </tr>

I need to extract only the string where the href = Municipality 我只需要提取其中href = Municipality的字符串

witch means Amos ,Angliers , etc... and store them into an array of string 女巫的意思是阿莫斯(Amos),天使(Angliers)等...并将它们存储在字符串数组中

So far I have tried this and I'm lost 到目前为止,我已经尝试过了,但我迷路了

  public static final String EXPRESSION = "";//How to write the regex expression?
String [] data = new String [20]
    URL url = new URL("http://myur.com");


 BufferedReader in  = new BufferedReader(new InputStreamReader(url.openStream()));

        while ((ligne = in.readLine()) != null) {
          //What to write here? 
            }
            in.close();

PS : I'm aware the best method is to use an HTML parser instead but I'm really forced to apply this way PS:我知道最好的方法是改用HTML解析器,但是我真的被迫采用这种方式

Much appreciation , 非常感谢,

Bass 低音

You can use something like this to hardcode match the url having municipalite and get the text inside wrt to > and < characters. 您可以使用类似这样的方法来硬编码匹配具有municipalite的网址,并将wrt中的文本获取为><字符。

This is my data file: 这是我的数据文件:

 <tbody>
                      <tr>
                        <td style="width: 14%;">88055</td>
                        <td style="width: 19%;" class="gris">Ville</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/88055/" >Amos</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/880/" >Abitibi</a></td>
                      </tr>
                      <tr>
                        <td style="width: 14%;">85080</td>
                        <td style="width: 19%;" class="gris">Village</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/85080/" >Angliers</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/850/" >Témiscamingue</a></td>
                      </tr>
                      <tr>
                        <td style="width: 14%;">87050</td>
                        <td style="width: 19%;" class="gris">Municipalité</td>
                        <td style="width: 33%;"><a href="repertoire-des-municipalites/fiche/municipalite/87050/" >Authier</a></td>
                        <td style="width: 34%;"><a href="repertoire-des-municipalites/fiche/mrc/870/" >Abitibi-Ouest</a></td>
                      </tr>

Here is the java file: 这是Java文件:

import java.util.*;
import java.util.regex.*;
import java.lang.*;
import java.io.*;

class test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BufferedReader in  = new BufferedReader(new FileReader(new File("data")));
        String line="";
        Pattern p=Pattern.compile("href\\s*=\\s*(?:\"|').*municipalite/[^>]*>(?:<.*>)*([^<]*)<.*$");
        while ((line = in.readLine()) != null)
        {
            Matcher m=p.matcher(line);
            while(m.find())
                System.out.println(m.group(1)); 
        }
        in.close();
    }
}

Output: 输出:

$ javac test.java 
$ java test 
Amos
Angliers
Authier
$

Regular expression breakdown: 正则表达式细分:

href\\s*=\\s*(?:\"|').*municipalite/[^>]*>(?:<.*>)*([^<]*)<.*$
  1. href\\\\s*=\\\\s* matches href following by 0 or more spaces followed by = and then 0 or more spaces href\\\\s*=\\\\s*匹配href,后跟0或多个空格,后跟= ,然后是0或多个空格

  2. (?:\\"|') -> (?:) means a non capturing group ie it matches single or double quotes but doesn't capture/remember it (?:\\"|') -> (?:)表示非捕获组,即它匹配单引号或双引号,但不捕获/记住它

  3. .*municipalite/ matches any char till municipalite/ occurs .*municipalite/匹配任何字符,直到municipalite/出现

  4. [^>]*>(?:<.*>)* matches any char that is not a > for the rest of the url and then matches > , then tries to match 0 or more (all optional) opening tags into a non capturing group using this (?:<.*>) [^>]*>(?:<.*>)*匹配URL其余部分中不是>任何字符,然后匹配> ,然后尝试将0个或多个(所有可选)打开标记匹配为一个非使用此捕获组(?:<.*>)

  5. ([^<]*) this group actually captures your string into group 1 ([^<]*)该组实际上将您的字符串捕获到组1中

  6. <.*$ matches the rest of the line <.*$与行的其余部分匹配

I have shown in python. 我已经在python中显示了。 But the regex is the same in Java, I believe. 但是,我相信Java中的正则表达式是相同的。 Use Java functions to find the matches. 使用Java函数查找匹配项。

import re
reg = r"<a href=.*?municipalite.*?>(.+?)</a>"
result = re.findall(html)

Try ".*\\\\bhref=\\"repertoire-des-municipalites/fiche/municipalite/\\\\d+/\\"[^>]*>([^<]*)<.*" 尝试".*\\\\bhref=\\"repertoire-des-municipalites/fiche/municipalite/\\\\d+/\\"[^>]*>([^<]*)<.*"

My demo code (below) gives console output: 我的演示代码(如下)给出了控制台输出:

Console Output 控制台输出

Amos
Angliers
Authier

Demo Code 示范代码

public class HrefRegex
{
    public static void main(final String[] args)
    {
        final String[] sampleLines = new String[] {
            "  </tr>",
            "    <td style=\"width: 14%;\">88055</td>",
            "    <td style=\"width: 19%;\" class=\"gris\">Ville</td>",
            "    <td style=\"width: 33%;\"><a href=\"repertoire-des-municipalites/fiche/municipalite/88055/\" >Amos</a></td>",
            "    <td style=\"width: 34%;\"><a href=\"repertoire-des-municipalites/fiche/mrc/880/\" >Abitibi</a></td>",
            "  </tr>",
            "  <tr>",
            "    <td style=\"width: 14%;\">85080</td>",
            "    <td style=\"width: 19%;\" class=\"gris\">Village</td>",
            "    <td style=\"width: 33%;\"><a href=\"repertoire-des-municipalites/fiche/municipalite/85080/\" >Angliers</a></td>",
            "    <td style=\"width: 34%;\"><a href=\"repertoire-des-municipalites/fiche/mrc/850/\" >Témiscamingue</a></td>",
            "  </tr>",
            "  <tr>",
            "    <td style=\"width: 14%;\">87050</td>",
            "    <td style=\"width: 19%;\" class=\"gris\">Municipalité</td>",
            "    <td style=\"width: 33%;\"><a href=\"repertoire-des-municipalites/fiche/municipalite/87050/\" >Authier</a></td>",
            "    <td style=\"width: 34%;\"><a href=\"repertoire-des-municipalites/fiche/mrc/870/\" >Abitibi-Ouest</a></td>",
            "  </tr>",
          };


        final Pattern pattern = Pattern.compile(".*\\bhref=\"repertoire-des-municipalites/fiche/municipalite/\\d+/\"[^>]*>([^<]*)<.*");

        for (final String s : sampleLines)
        {
            final Matcher matcher = pattern.matcher(s);

            if (matcher.matches())
            {
                System.out.println(matcher.group(1));
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM