从页面上的许多匹配链接获取链接?

时间:2015-06-02 13:06:54

标签: php html dom

我正在使用SDK platform抓取远程页面的HTML,在这个远程页面中,我可以使用file_get_contents()抓取大量链接。

但我遇到的问题是我想要的链接包含一个特定值' / vue /',页面上有1到1000个链接,其中包含相同的值它。 $dom部分是链接中唯一的静态元素。

我只需要其中一个链接,哪一个并不重要 我怎样才能从大量的链接中抓取一个链接?

以下是我目前获取所有链接的代码:

/vue/

foreach($dom->getElementsByTagName('a') as $node) { if(strpos($node->getAttribute('href'),'/vue/') !== false) { $Epsiodes = $node->getAttribute('href')[0]; } } 空白。

1 个答案:

答案 0 :(得分:1)

使用XPath(以及DOMDocument::loadHTMLFile代替file_get_contents)将更直接地做到这一点:

$dom = new DOMDocument;
$dom->loadHTMLFile($url);

$xp = new DOMXPath($dom);

$hrefNodeList = $xp->query('//a/@href[contains(., "/vue/")][1]');

if ($hrefNodeList->length)
    $result = $hrefNodeList->item(0)->nodeValue;

XPath查询详情:

//    # anywhere in the DOM tree
a     # "a" tag
/
@href # href attribute
[     # start a condition
  contains(., "/vue/")  # the current element `.` must contain `/vue/`
]     # close the condition
[1]   # only one item (the first)

请注意,即使只有一个结果DOMXPath::query,也会返回一个节点列表(但只有一个元素)

相关问题