xpath:使用xpath从节点提取数据

时间:2012-01-19 07:28:39

标签: php xpath domxpath

我想只提取销售排名(在这种情况下为5)

  

亚马逊畅销书排名: #5   书籍(见   书籍前100名)

来自网页:http://www.amazon.com/Mockingjay-Hunger-Games-Book-3/dp/0439023513/ref=tmm_hrd_title_0

到目前为止,我已经了解了这一点,选择了亚马逊畅销书排名:":

//li[@id='SalesRank']/b/text()

我使用的是PHP DOMDocumentDOMXPath

2 个答案:

答案 0 :(得分:2)

您可以使用纯XPath:

substring-before(normalize-space(/html/body//ul/li[@id="SalesRank"]/b[1]/following-sibling::text()[1])," ")

但是,如果您的输入有点乱,您可以通过使用XPath获取父节点的文本,然后在文本上使用正则表达式来获取您想要的特定内容,从而获得更可靠的结果。

使用PHP DOMDocumentDOMXPath

演示这两种方法
// Method 1: XPath only
$xp_salesrank = 'substring-before(normalize-space(/html/body//li[@id="SalesRank"]/b[1]/following-sibling::text()[1])," ")';

// Method 2: XPath and Regex
$regex_ranktext = 'string(/html/body//li[@id="SalesRank"])';
$regex_salesrank = '/Best\s+Sellers\s+Rank:\s*(#\d+)\s+/ui';

// Test URLs
$urls = array(
    'http://rads.stackoverflow.com/amzn/click/0439023513',
    'http://www.amazon.com/Mockingjay-Final-Hunger-Games-ebook/dp/B003XF1XOQ/ref=tmm_kin_title_0?ie=UTF8&m=AG56TWVU5XWC2',
);

// Results
$ranks = array();
$ranks_regex = array();

foreach ($urls as $url) {
    $d = new DOMDocument();
    $d->loadHTMLFile($url);
    $xp = new DOMXPath($d);

    // Method 1: use pure xpath
    $ranks[] = $xp->evaluate($xp_salesrank);

    // Method 2: use xpath to get a section of text, then regex for more specific item
    // This method is probably more forgiving of bad HTML.
    $rank_regex = '';
    $ranktext = $xp->evaluate($regex_ranktext);
    if ($ranktext) {
        if (preg_match($regex_salesrank, $ranktext, $matches)) {
            $rank_regex = $matches[1];
        }
    }
    $ranks_regex[] = $rank_regex;

}

assert($ranks===$ranks_regex); // Both methods should be the same.
var_dump($ranks);
var_dump($ranks_regex);

我得到的输出是:

array(2) {
  [0]=>
  string(2) "#4"
  [1]=>
  string(2) "#3"
}
array(2) {
  [0]=>
  string(2) "#4"
  [1]=>
  string(2) "#3"
}

答案 1 :(得分:0)

使用

substring-before(substring-after($expr, '#'), ' ')

$expr应由您的表达式替换

   substring-before(substring-after(//li[@id='SalesRank']/b, '#'), ' ')

或者,如果选择文本节点的正确表达式是(根据@FrancisAvila):

/html/body//ul/li[@id="SalesRank"]/b[1]/following-sibling::text()[1]

然后上面变成了:

substring-before(
   substring-after(/html/body//ul/li[@id="SalesRank"]
                  /b[1]/following-sibling::text()[1], '#'), 
   ' ')