我想要使用JSONP获取源代码形式的URL网页。 这是代码:使用JSONP从JavaScript网页获取源代码使用JSONP
<script type="text/javascript">
var your_url = '';
$(document).ready(function(){
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if (/get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url)) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: your_url,
type: 'GET',
success: function(res) {
var text = res.responseText;
//document.getElementById("contenuto").innerHTML = text;
alert(text);
}
});
});
</script>
我印有一个警报的所有源代码,从所述URL。
alert(text);
首先,如何知道打印的代码是否是页面的所有网页代码? 如果我尝试这样做
document.getElementById("contenuto").innerHTML = text;
这就是结果:
\ \ <'+'/ins>\ \ \ '); } ]]>
我试图用HTML DOM打印一个元素,这样
document.getElementById("contenuto").innerHTML = text;
var elem = text.getElementById("strip_adv").innerHTML;
document.getElementById("contenuto_1").innerHTML = elem;
}
做
但是,这是JS控制台上的错误:
text.getElementById is not a function
概述: 我想使用JSONP从URL获取网页的源代码。 我会从返回的文本中使用HTML DOM,只保留我需要的元素/类。我是JS的新手,我想了解更多关于JS的&。
'responsetext'不是元素。你应该尝试解析它。 – mok
@mok如果我试图使用此代码打印 document.getElementById(“contenuto”)。innerHTML = text; 这是结果是:[screen1](https://postimg.org/image/erjvgz9s7/) 为什么?首先,我打印整个“字符串”(页面的源代码),检查它是否完整。但我不能。 – Jackie
似乎你的代码没有正确解析页面。试试这样一个简单的页面[http://www.murgaboots.com/aboutus.html](随机选择一个简单的网页)。无论如何,答案就是我之前说过的,你应该解析'responsetext'。 – mok