-2
我需要从同一网站的很多网页复制链接。 看起来像:/download.php?id=xxxxx 只需要添加1更多的ID有所需的网页... 在这些网页上,我需要采取代码内的链接: href =“http: //www.site.com/xxxxxxxxxxxx“ (x作为变量)复制大量网页链接的脚本
有可能吗? 感谢
我需要从同一网站的很多网页复制链接。 看起来像:/download.php?id=xxxxx 只需要添加1更多的ID有所需的网页... 在这些网页上,我需要采取代码内的链接: href =“http: //www.site.com/xxxxxxxxxxxx“ (x作为变量)复制大量网页链接的脚本
有可能吗? 感谢
不要使用正则表达式来解析HTML
或许最大的错误的人试图从网页获取网址或链接文本尝试使用正则表达式来做到这一点的时候做。这项工作可以用正则表达式来完成,但是,在多次遍历整个文档时,会有很高的开销。正确的方式,更快,更酷的方式是使用DOM。 通过在getLinks函数中使用DOM,可以很简单地创建一个数组,其中包含网页上的所有链接作为关键字,并将链接名称作为值。然后这个数组可以像任何数组和列表一样循环,创建或者以任何想要的方式操作。 请注意,加载HTML时使用了错误抑制。这是为了抑制有关DOCTYPE中未定义的无效HTML实体的警告。但是,当然,在生产环境中,错误报告将被禁用并且错误报告设置为无。
<?php
function getLinks($link){
$ret = array();
/*** a new dom object ***/
$dom = new domDocument;
/*** get the HTML via FGC,
Tho prefer using cURL instead but that's out of scope of the question..
(@suppress those errors) ***/
@$dom->loadHTML(file_get_contents($link));
/*** remove silly white space ***/
$dom->preserveWhiteSpace = false;
/*** get the links from the HTML ***/
$links = $dom->getElementsByTagName('a');
/*** loop over the links ***/
foreach ($links as $tag){
/*** only add download links to the return array ***/
if(strpos($tag->getAttribute('href'),'/download.php?id=')!=false){
$ret[$tag->getAttribute('href')] = $tag->childNodes->item(0)->nodeValue;
}
}
return $ret;
}
?>
使用示例
<?php
/*** a link to search ***/
$link = "http://www.site.com";
/*** get the links ***/
$urls = getLinks($link);
/*** check for results ***/
if(sizeof($urls) > 0){
foreach($urls as $key=>$value){
echo $key . ' - '. $value . ' - ' . str_ireplace('http://www.site.com/download.php?id=','',$key). '<br >';
}
}else{
echo "No links found at $link";
}
?>
是的,这是可能的。 –
你到目前为止尝试过什么,你为自己做了什么尝试? PS不去与正则表达式的方法... –