Google App Script parse table from messed html

2019-08-04 13:45发布

I want to create a script which download html, parse a table and save it to a SpreadSheet. I am stuck on downloading and parsing.

Xpath to table is:

/html/body/table/tbody/tr[5]/td/table/tbody/tr/td[2]/table

Currently I am stuck at parsing Xpath.

function fetchIt() {
var fetchString="http://www.zbranebrymova.com/index.php?s_lev=22&type=nabku*signa"
var response = UrlFetchApp.fetch(fetchString);

var xmlDoc = Xml.parse(response.getBlob().getDataAsString(),true);
var b = xmlDoc.getElement().getElement("body").getElement("table") ;

Logger.log(b);
}

1条回答
Anthone
2楼-- · 2019-08-04 14:08

I don't know if this will be helpful, here is a snippet of my table parsing code:

html file FOO.HTM:

<html>
<head> </head>
<body style="margin-left:10px">
  <table title="">
    <tbody>
      <tr>
        <th align="center" abbr="Sunday">Sun</th>
        <th align="center" abbr="Monday">Mon</th>
      </tr>
      <tr>
        <td align="left"><a title="January 01">1</a>
          <div>Joe,Doe</div>
          <div>Murphy,Jack</div>
        </td>
        <td align="left"><a title="January 02">2</a>
          <div>Carlson,Carl</div>
          <div>Guy,Girl</div>
          <div>Lenin,Vladimir</div>
        </td>
      </tr>
    </tbody>
  </table>
</body>
<html>

and this is how I parse it:

function foo() {
  var page = UrlFetchApp.fetch('foo.htm');
  var rows = Xml.parse(page,true).getElement()
      .getElement("html")
      .getElement("body")
      .getElement("table")
      .getElement("tbody")
      .getElements("tr");

  for (var ii = 0; ii < rows.length; ii++) {
    var cols = rows[ii].getElements("td");
    for (var jj = 0; jj < cols.length; jj++) {
      var divs = cols[jj].getElements("div");
      for (var kk = 0; kk < divs.length; kk++) {
        var div = divs[kk];
      }
    }
  }
}

cheers, sean

查看更多
登录 后发表回答