uiwebview JavaScript HTML 仅获取面向用户的正文文本

uiwebview javascript HTML get user facing body text only

本文关键字:正文 文本 面向用户 获取 JavaScript HTML uiwebview      更新时间:2023-09-26

我在UIWebView
中加载了以下html源代码我想提取
文本1
文本2 文本2
文本3 文本3 文本3

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>1322170516271</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=1, minimum-scale=1.0, maximum-scale=4.0">                   
    <style type="text/css">
    body
    {
        padding: 5px;
        margin: 0px;
        font-family: Helvetica, Arial;
        font-size: 12pt;
        background-color: #efefef;
        background-image: url(ArticleBackground.jpg);
        background-position: cover;
        color: #000000;
    }
    h1
    {
        text-align: center;
        border-bottom: 1px dotted #805050;
        font-size: 28px;
        line-height: 38px;
        margin-bottom: 30px;
        text-shadow: 0 2px 1px white;
        color: #803030;
    }
    </style>
</head>
<body>
    <script type="text/javascript">
    function printMe()
    {
        print();
    }
    </script>
    <div style='align:center; padding: 20px;'>
        <div>
    <b>text1</b><br><br>
    <h2>
      text2 text2
    </h2>
    <br>
    text3 text3 text3
        </div>
    </div>
</body>
</html>

但这是我使用时得到的

[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"]

我不需要身体和h1。我只想要面向用户的实际文本。

234534546

    body
{
    padding: 5px;
    margin: 0px;
    font-family: Helvetica, Arial;
    font-size: 12pt;
    background-color: #efefef;
    background-image: url(ArticleBackground.jpg);
    background-position: cover;
    color: #000000;
}
h1
{
    text-align: center;
    border-bottom: 1px dotted #805050;
    font-size: 28px;
    line-height: 38px;
    margin-bottom: 30px;
    text-shadow: 0 2px 1px white;
    color: #803030;
}



    function printMe()
    {
        print();
    }



text1

  text2 text2

text3 text3 text3

感谢您的任何见解。

更新

[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"] 也不适用于我的目标

<script type="text/javascript">
    function printMe()
    {
        print();
    }
    </script>
    <div style="align:center; padding: 20px;">
        <div>
    <b>text1</b><br><br>
    <h2>
       text2 text2
    </h2>
    <br>
    text3 text3 text3
        </div>
    </div>

更新:这是现有项目所必需的。如果我有机会重新设计它,解决方案将很容易找到。但是考虑到这个HTML源代码,它可能会使它有点困难。

尝试使用 :

document.body.innerHTML

或者看看解析 HTML:在 iPhone 上解析 HTMLSO上还有许多其他链接。

为什么

不将所有文本放入不同的标签中,例如div,p等。 给它们每个人 id,然后通过语法获取其中的文本

var text1 = document.getElementById("your ID").innerHTML

希望这适用于您的问题。