如何使用jQuery阅读网页并提取某些链接

How to Read a webpage and extract certain links using jQuery?

本文关键字:提取 链接 网页 何使用 jQuery      更新时间:2023-09-26

在同一个域名上。我的Jquery代码和url读取。

我想做的是首先使用Jquery读取网页,然后解析某些链接,其中有"ProductDetails.php"和提取"ProductCode"从网页到数组。

html页面可能有许多href="ProductDetails.php实例,如下所示。

<a href="ProductDetails.php?ProductCode=SMS%2D15%2DXLG%2DA7&CartID=1" class="carttext colors_productname cart-item-name">item 1 <a>
<a href="ProductDetails.php?ProductCode=SMS%dfdfde&CartID=2" class="carttext colors_productname cart-item-name">test me item <a>

我不知道这是否真的可能

你必须这样做:

var filteredAnchors = $( document.body ).find( 'a' ).map(function( _, anchor ) {
   if( anchor.getAttribute('href').indexOf( 'ProductDetails.php' ) === 0 ) {
       return anchor.getAttribute('href').match( /ProductCode=(.*?)&/ )[ 1 ];
   }
}).get();

filteredAnchors现在应该包含所有的产品代码。

示例:http://jsfiddle.net/WgwSr/

像这样的东西应该让你开始:

$.ajax({
    url: "pagetoload.html",
    success: function(htmlofthepage) {
        var html = $(htmlofthepage),
            resultarray = []; // the array containing our final result set
        // getting all of the anchor tags we want to look at
        $('a[href^="ProductDetails.php"]', html).each(function () {
            var t = $(this), // the anchor tag
                href = t.prop('href'), // the href of the tag (eg. ProductDetails.php?...)
                start = href.indexOf('ProductCode', 0),
                begin = 0,
                end = 0;
            if (start > -1) {
                begin = href.indexOf('=', start) + 1;
                end = href.indexOf('&', begin);
                resultarray.push(href.split(begin, end));
            }
        });
    }
});

使用jQuerys的each函数:

   jQuery(function($){
     var links = [];
     $("a[href^=ProductDetails.php]").each(function(){
        links.push(this.href.replace(/^.*'?/,'');
     });
   });