AS3:如何从HTML&获取特定数据?拆分它

时间:2014-01-09 11:45:01

标签: actionscript-3 loader

我试图从我的学校项目的网站获取“可见性”数据,我尝试了跟踪,跟踪(loader.data [“Visibility”]); ,但它不起作用

这是代码

var url:String = "http://www.bbc.co.uk/weather/1880252";
var reqURL:URLRequest = new URLRequest(url);
var loader:URLLoader = new URLLoader(reqURL);


loader.addEventListener(Event.COMPLETE, handleComplete);
loader.dataFormat = URLLoaderDataFormat.TEXT;

function handleComplete(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
trace(loader.data);
}

1 个答案:

答案 0 :(得分:1)

在AS3(而不是AIR)中解析原始html没有通用的方法或任何内置函数。 在您的情况下,最简单的方法是使用RegExp

public function astest()
{
    var url:String = "http://www.bbc.co.uk/weather/1880252";
    var reqURL:URLRequest = new URLRequest(url);
    var loader:URLLoader = new URLLoader(reqURL);


    loader.addEventListener(Event.COMPLETE, handleComplete);
    loader.dataFormat = URLLoaderDataFormat.TEXT;

    function handleComplete(event:Event):void
    {
        var loader:URLLoader = URLLoader(event.target);

        var rawhtml:String = loader.data;

        // <tr class="visibility">
        var tag:String = rawGetTagByAttrValue(rawhtml, "visibility", "tr", "class");
        trace(tag);
    }
}

public static function rawGetTagByAttrValue(html:String, attrValue:String, tag:String = "",  attrName:String = ""):String
{
    var pattern:RegExp = tag == "" ? 
            new RegExp("<(\\w+)[^>]+?"+attrName+"=\""+attrValue+"\".*?(/>|</\\1>)","is") :
            new RegExp("<"+tag+"[^>]+?"+attrName+"=\""+attrValue+"\".*?(/>|</"+tag+">)","is");

    var result:Array = html.match(pattern);  

    if (result != null && result.length > 0)
        return result[0];

    return "";
}

输出:

<tr class="visibility">
        <th class="row-title">Visibility (E = Excellent, VG = Very Good, G = Good, M = Moderate, P = Poor, VP = Very Poor)</th>
                        <td class="value hours-3"
                ><abbr title="Good">G</abbr
                ></td>
                        <td class="value hours-3"
                ><abbr title="Good">G</abbr
                ></td>
                        <td class="value hours-3"
                ><abbr title="Good">G</abbr
                ></td>
                        <td class="value hours-3"
                ><abbr title="Good">G</abbr
                ></td>
                    <td class="hours-3 empty">&nbsp;</td><td class="hours-3 empty">&nbsp;</td><td class="hours-3 empty">&nbsp;</td><td class="hours-3 empty">&nbsp;</td>        </tr>