【问题标题】:How find all links (URL) in a webpage and add a string at the end of all of them?如何找到网页中的所有链接(URL)并在所有链接的末尾添加一个字符串?
【发布时间】:2015-05-30 01:52:16
【问题描述】:

嘿,所以我想要实现的是使用

获取页面上的所有链接
preg_match_all("/<a(?:[^>]*)href=\"([^\"]*)\"(?:[^>]*)>(?:[^<]*)<\/a>/is"

然后在每个网址的末尾添加“|Cookie=”,同时保持页面来源完全相同。

例如: 假设我在抓取的页面“example.com/index.htmlexample2.com/index.html”中找到以下链接

我希望将它们更改为“example.com/index.html|Cookie=xxx”和“example2.com/index.html|Cookie=xxx

如果我的问题太含糊,很抱歉。我不知道如何开始:(

【问题讨论】:

    标签: php html regex string web-crawler


    【解决方案1】:

    您不需要正则表达式,您可以使用 DOM 为您完成此操作。

    $doc = new DOMDocument;
    @$doc->loadHTML($html); // load the HTML data
    
    foreach ($doc->getElementsByTagName('a') as $link) {
       $link->setAttribute('href', $link->getAttribute('href').'|Cookie=xxx');
    }
    
    echo $doc->saveHTML();
    

    【讨论】:

    【解决方案2】:

    如果您有网址,只需替换 $content = file_get_contents('URL');

    <?php
    
    $content = '<html>
    <title>Random Website I am Crawling</title>
    <body>
    Click <a href="http://clicklink.com">here</a> for foobar
    Another site is http://foobar.com
    </body>
    </html>';
    
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
    
    $pattern = "/$regex/";
    
    $newContent = preg_replace($pattern, '${0}|Cookie=xxx', $content);
    echo $newContent;
    

    输出:

    <html>
    <title>Random Website I am Crawling</title>
    <body>
    Click <a href="http://clicklink.com|Cookie=xxx">here</a> for foobar
    Another site is http://foobar.com|Cookie=xxx
    </body>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      相关资源
      最近更新 更多