我如何在 React Native 中解析 HTML 文件?

新手上路,请多包涵

如何从文件系统获取 HTML 文件并从中解析特定元素。

例如,给定下面的 html 片段,我如何提取表格内容并呈现它?

 <html>
<div>
  <h1>header</h1>
  <table id="a" border="1">
    <th>Number</th>
    <th>content A</th>
    <th>contetn A</th>
    <th>content A</th>
    <tr>
      <td>1</td>
      <td>a</td>
      <td>a</td>
      <td>a</td>
    </tr>
    <th>Number</th>
    <th>content B</th>
    <th>content B</th>
    <th>content B</th>

    <tr>
      <td>1</td>
      <td>b</td>
      <td>b</td>
      <td>b</td>
    </tr>
  </table>
</div>
<br>
<footer>footer</footer>

</html>

原文由 Dmitry Petukhov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 800
2 个回答

只需使用 fetch() 下载 HTML,使用 fast-html-parser 解析它,将结果写入状态并使用 WebView 呈现该状态

原文由 Dmitry Petukhov 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 fetch() 获取 html,使用 react-native-html-parser 解析,使用 WebView 处理和显示。

 import DOMParser from 'react-native-html-parser';

fetch('http://www.google.com').then((response) => {
   const html = response.text();
   const parser = new DOMParser.DOMParser();
   const parsed = parser.parseFromString(html, 'text/html');
   parsed.getElementsByAttribute('class', 'b');
});

来自其他答案的 PS fast-html-parser 对我不起作用。使用 react-native 0.54 安装时出现多个错误。

原文由 ljmocic 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题