基于Web的应用程序HTML解析

2024-09-30 02:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个基于web的应用程序,它使用对http://www.whateverorigin.org/的调用加载URL的HTML内容,这避免了同一源策略冲突

url = 'http://' + document.getElementById("urlText").value
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(url) + '&callback=?', function(data){
var doc = new DOMParser().parseFromString(data.contents, 'text/html');  

如果我需要从这个html字符串中提取有意义的可见文本,有没有一种方法可以像beautifulsoup在python中那样做呢?我更像是javascript的初学者。你知道吗


Tags: orgweb应用程序httpurl内容datahtml
2条回答

看起来这就是你需要的?下面的代码分析谷歌.nl与whateverorigin.org网站网站,并将其添加到一个div。如果没有,请尝试解释你还需要什么!你知道吗

jQuery:

$(document).ready(function() { $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://www.google.nl') + '&callback=?', function(data){ $('.result').html(data.contents); }); });

HTML:

<div class="result"></div>

例如:http://jsfiddle.net/qddekhnc/1/

使用jQuery查找并iterate覆盖适当的元素。然后您可以决定打印出什么-例如:显示可见项的文本节点。 下面是一个jsfiddle和一个工作脚本示例:http://jsfiddle.net/w147o9f6/1/

<body>
    <div id="outputTexts">OUTPUT:</div>
</body>

javascript代码:

var parser = new DOMParser();
var doc;
var meaningfulTexts = [];
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('https://www.facebook.com') + '&callback=?', function(data){
    doc = parser.parseFromString(data.contents, "text/html");

    var ELMS = $(doc).find("div, p, a, span");
    ELMS.each(function(index, element) {
        if(element.style.display != "none" && $(element).text() != "") {
            $("#outputTexts").append('<br>'+ element.tagName + ' - '+$(element).text());
            meaningfulTexts.push( $(element).text() );
        }
    });
});

相关问题 更多 >

    热门问题