【问题标题】:Extract Data From Plain HTML从纯 HTML 中提取数据
【发布时间】:2015-12-09 02:19:07
【问题描述】:

我有一个 html 的 sn-p,其中包含邮政编码的第一部分及其所在的区域。两行的示例:

<tr height="17">
  <td class="xl66" height="17">Channel Islands</td>
  <td class="xl66">GY - (Guernsey)</td>
</tr>
<tr height="17">
  <td class="xl66" height="17">Channel Islands</td>
  <td class="xl66">JE - (Jersey)</td>
</tr>

如何/我可以使用什么来提取区域和邮政编码减去位置名称的部分。

从示例数据中,我想检索('Channel Islands', 'GY'), ('Channel Islands', 'JE'),以便将它们输入数据库。

【问题讨论】:

  • 你用的是什么操作系统?Linux还是windows?
  • 应该使用哪种语言?
  • 您是否使用 PHP 作为后端?和 MySQL 的数据库?

标签: html regex extract


【解决方案1】:

使用 GAWK

证明使用 gawk 脚本语言是值得的

创建一个文件名gawkscript 并添加以下内容:

#Test to see if the line matches the region, if it does, use regex to get your region
$0~/<td class="xl66" height="17">Channel Islands<\/td>/{printf gensub(/ *<td.*>(.+)<\/td>/,"\\1,",$0)};

#Test to see if the line matches the cose, if it does, use regex to get your code
$0~/<td class="xl66">(.+)<\/td>/{print gensub(/ *<td.*>(.+) *- \(.+\)<\/td>/,"\\1",$0)}

使用你的 shell 你可以运行脚本

gawk -f gawkscript   my_html_file

由于这是我们正在处理的 html 代码,我会在 python 调用 BeautifulSoup 中使用一个强大的 html 网页抓取模块

使用 Python 假设你知道一些 python

import re #import regex
from bs4 import BeautifulSoup #import beautifulsoup
soup=BeautifulSoup(
#add your html string
    """<tr height="17">
  <td class="xl66" height="17">Channel Islands</td>
  <td class="xl66">GY - (Guernsey)</td>
</tr>

<tr height="17">
  <td class="xl66" height="17">Channel Islands</td>
  <td class="xl66">JE - (Jersey)</td>
</tr>""")
#find all tr tags in your html string 
find_all_tr=soup.find_all("tr")  
for i in find_all_tr: #loop through all tr tags
        all_td=BeautifulSoup(str(i)).find_all("td") #find all td tags
        for j in all_td:
#check to see if your td tages matches 'td class="xl66" height="17"' and print
            if re.search('<td class="xl66" height="17"',str(j)): 
                print(j.text.strip(),end=" ")
#check to see if your td tag matches ONLY <td class="xl66" and use regex to obtain your country code
            elif re.search('<td class="xl66">',str(j)):
                print(","+re.sub(".*-","",j.text.strip()))

注意:我在这里使用 strip() 函数,因为 html 可以在提取信息时消除 html 代码中不需要的换行符

【讨论】:

  • 这是一个 python3x 脚本而不是 2x
【解决方案2】:

在不了解语言 (PHP/ASP) 和数据库 (MySQL/NoSQL) 等服务器端细节的情况下,我无法向您展示如何处理后端代码。

话虽如此,下面的代码向您展示了如何在客户端处理和准备数据,并通过 JavaScript 向您的服务器发出异步 (POST) 请求。


相关信息:

这是一个有据可查的指南 -- FormData( ) object

这是一个有据可查的指南 -- XMLHttpRequest( ) object


截图:


//HTML (index.html)

<!DOCTYPE html>
<html>
<head>
    <script src="index.js"></script>
    <link rel="stylesheet" href="index.css">
</head>
<body>
<button onclick="submitTable();">Click Me</button>
<table>
    <thead>
        <tr>
            <th>Region</th>
            <th>Postcode</th>
        </tr>
    </thead>
    <tbody>
        <tr class="data-row">
            <td>Channel Islands</td>
            <td>GY - (Guernsey)</td>
        </tr>
        <tr class="data-row">
            <td>Channel Islands</td>
            <td>JE - (Jersey)</td>
        </tr>
    </tbody>
</table>
</body>
</html>

//JS(index.js)

function submitTable(){
    //OBJECT INITIALIZATION
    if (window.XMLHttpRequest){ 
        var request = new XMLHttpRequest();  // IE7+, Firefox, Chrome, Opera, Safari                     
    }
    else{ 
        var request = new ActiveXObject("Microsoft.XMLHTTP"); // IE 6 and older
    }
    var formData = new FormData();
    
    //LOOP THROUGH DATA and APPEND to FormData(object)
    var dataRows = document.getElementsByClassName("data-row");
    for(var i=0; i < dataRows.length; i++){
        var data = dataRows[i].children;
        for(var x=0; x < data.length; x++){
            if(x === 1){
                var postcode = data[x].innerHTML.substr(0, 2);
                formData.append("postcode", data[x].innerHTML);
            }
            else{
                formData.append("region", data[x].innerHTML);
            }
        }
    }
    //OPEN
    request.open("POST", "/path/to/post/the/data");
    //SEND
    request.send(formData);
    //RESPONSE
    request.onreadystatechange = function(){
        if(request.readyState == 4){
            console.log(request.response);
        }
    }
}

//CSS (index.css)

table, th, td {
    border: 1px solid black;
}

【讨论】:

    【解决方案3】:

    你可以使用正则表达式

    /<td.*?>(.*?)<\/td.*?>\s+<td.*?>(.*?)\s-.*?<\/td>/gi
    

    Regex explanation here

    【讨论】:

    • 你为什么使用&lt;\/td.*?&gt;?闭合节点不能有属性。还有一个提示:当你想匹配节点的内部时,永远不要使用.*。
    • 正则表达式太不安全,无法从 HTML 代码中解析出值,而您使用惰性点匹配使其更加不安全。无论如何,如果有人认为它有价值,让他们投票吧:)
    【解决方案4】:

    我可以在 javascript 的帮助下完成您的工作,因为我对正则表达式的了解较少。

    这里是JS代码:

    var array = [];
    var table = document.getElementById('myTable');
    var rowLength = table.rows.length;
    for (i = 0; i < rowLength; i++) {
      var collect = [];
      var col = table.rows.item(i).cells;
      var colLength = col.length;
      for (var j = 0; j < colLength; j++) {
        var value = col.item(j).innerHTML;
        collect.push(value);
      }
      array.push(collect);
    }
    

    这是工作链接

    http://plnkr.co/edit/8e67Il0u5dmr6NZX3FWJ?p=preview
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2012-08-01
      • 2012-11-22
      • 2020-09-30
      • 1970-01-01
      相关资源
      最近更新 更多