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

Dmi*_*hov 8 html javascript html-parsing react-native

如何从文件系统获取 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>
Run Code Online (Sandbox Code Playgroud)

Dmi*_*hov 5

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

  • 你使用什么反应本机版本?我尝试过从 43 到 44,但模块“fast-html-parser”有同样的问题: UnableToResolveError: Unable to parse module `util` from `/.../node_modules/apollojs/server.js` 您的版本是什么package.json 在这些行中?: "react": "^16.0.0-alpha.6", "react-native": "^0.43.4" (3认同)
  • 不适用于 React Native 0.41.2,与@Stich 相同的问题 (3认同)
  • 您好,这是这个问题的答案,如果您使用 npm install util 显式安装 util,则可以解决此问题。https://github.com/ashi009/node-fast-html-parser/issues/11 (2认同)
  • 它运行良好,但您需要运行“npm install util”来解析模块 util (2认同)

ljm*_*cic 5

使用 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');
});
Run Code Online (Sandbox Code Playgroud)

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


joh*_*ges 3

我建议使用这个库:react-native-htmlviewer。它采用 html 并将其呈现为本机视图。您还可以自定义元素的渲染方式。

// only render the <table> nodes in your html
function renderNode(node, index, siblings, parent, defaultRenderer) {
  if (node.name !== 'table'){
    return (
      <View key={index}>
        {defaultRenderer(node.children, parent)}
      </View>
    )l
  }

}

// your html
const htmlContent = `<html></html>`;

class App extends React.Component {
  render() {
    return (
      <HTMLView value={htmlContent} renderNode={renderNode} />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)