doushan6161 2012-09-06 23:04
浏览 74
已采纳

PHP正则表达式 - 使用指定类从所有链接获取文本[重复]

Possible Duplicate:
How to parse and process HTML with PHP?

I'm trying to use PHP and regex to grab all the hyperlinks from an external page. The links I care about scraping are structured as follows:

<li class="magic"><a href="http://blah.com">TargetText1</a></li>
<li class="magic"><a href="http://blah.com">TargetText2</a></li>

Please bear in mind I'm trying to get the anchor text NOT the url. I've got the code below working however it simply scrapes all the links on the page. I'm trying to scrape links only wrapped with the li class listed above.

 $url = "http://www.example.com"; 
 $input = @file_get_contents($url) or die("Could not access file: $url"); 

 $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";

 if(preg_match_all("/$regexp/siU", $input, $matches)) { 
  print_r($matches);
 }
  • 写回答

1条回答 默认 最新

  • dongzaizai2015 2012-09-06 23:11
    关注
    <?php
    
        $dom = new domDocument;
        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;
        $lis = $dom->getElementsByTagName('li');
        foreach($lis  as $li){
            if($li->getAttribute('class')=='magic'){
                $links = $li->getElementsByTagName('a');
                if($links->length){
                    echo $links->item(0)->nodeValue;
                }
            }
        }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀