繁体   English   中英

使用jQuery和/或AJAX从网站提取当前图像?

[英]Using jQuery and/or AJAX to pull current images from a website?

我的任务是使用Wikipedia API从新泽西州的网站检索图像,我想出了两种方法来执行类似的任务。 第一种方法是使用JSON,但它提取了整个页面。

<script type="text/javascript">
$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
$('#wikiInfo').html(json.parse.text['*']); 
$("#wikiInfo").find("a:not(.references a)").attr("href", function(){ return "http://www.wikipedia.org" + $(this).attr("href");}); 
$("#wikiInfo").find("a").attr("target", "_blank"); 
});
</script>

<div id="wikiInfo">&nbsp;</div>

我还使用了与jQuery配对的AJAX请求,但它只提取了文本。

<script type="text/javascript">
    $(document).ready(function(){
$.ajax({
    type: "GET",
    url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&page=New_Jersey&callback=?",
    contentType: "application/json",
    async: false,
    dataType: "json",
    success: function (data, textStatus, jqXHR) {

    var markup = data.parse.text["*"];
    var i = $('<div></div>').html(markup);

    // remove links as they will not work
    i.find('a').each(function() { $(this).replaceWith($(this).html()); });

    // remove any references
    i.find('sup').remove();

    // remove cite error
    i.find('.mw-ext-cite-error').remove();

    $('#article').html($(i).find('p'));


    },
    error: function (errorMessage) {
    }
});    

});    

哪种方法最适合解决此问题,如何修复它以仅提取当前图像,以及将用户名分配给每张图片?

谢谢!

获取图像的一种可能方法是使用正则表达式

ES6版本:

$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
const text = json.parse.text['*'];
const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
let m;
while ((m = regex.exec(text)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    console.log(`Found match: ${m[1]}`);
}});

ES5版本:

$.getJSON('http://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) { 
var text = json.parse.text['*'];
var regex = /([-\w+\.\/]+(?:png|svg))/gmi;
var m;
while ((m = regex.exec(text)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    console.log('Found match: ' + m[1]);
}});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM