如何修改href链接(scraper)

时间:2011-01-09 21:57:18

标签: php html regex parsing dom

我正在抓取一个页面,但在回复我的内容之前,我想编辑该链接。

这样做的最佳方式是什么?

我目前正在使用Simple HTML DOM Parser:

// create HTML DOM
$html = file_get_html('http://myurl.com');
// remove all image
  foreach($html->find('img') as $e)
 $e->outertext = '';
foreach($html->find('font') as $e)
$e->outertext = '';
// find all td tags with attribite align=center
foreach($html->find('td[align=left]', 2) as $e)
   echo $e->innertext;

其中一个网址中有这一位:

<a target="retailer" href="/cgi-bin/redirect.cgi?name=Storm%20Computers&amp;linkid=2&amp;newurl=http%3A%2F%2Fwww.stormcomputers.com.au%2Fcatalog%2Findex.php%3FcPath%3D38_364&amp;query=sandy%20bridge&amp;uca=208-0-0&amp;kwi=&amp;rpos=2" title="Storm Computers: Click to see item">$149.00</a>

我想将此更改为

<a href="http%3A%2F%2Fwww.stormcomputers.com.au%2Fcatalog%2Findex.php%3FcPath%3D38_364&amp;query=sandy%20bridge&amp;uca=208-0-0&amp;kwi=&amp;rpos=2">$149.00</a>

(即刚刚&amp; newurl =)

感谢。

3 个答案:

答案 0 :(得分:1)

我不熟悉你正在使用的解析器,但是这样的东西可能会起作用:

foreach ($html->find('a') as $link) {
    $urlparts = parse_url($link->href);
    $query = parse_str($urlparts['query'], $params);

    if (isset($params['newurl'])) {
        $link->href = $params['newurl'];
    }
}

答案 1 :(得分:0)

找到与DOM的链接。之后,只需使用explode来分割href字符串。

$split_href = explode('&amp;newurl=', $href);

if(count($split_href) > 1) {
    $newurl = $split_href[1];
}

不要以为你需要正则表达式,因为它更慢。

答案 2 :(得分:0)

您可以使用正则表达式查找所有链接,然后使用parse_url()parse_str()重建链接。

例如:

if (preg_match_all('/<a href="(.+)">(.+)<\/a>/i',$html,$matches)) {

  // at this point, $matches is a multidimensional array where
  // index 0 is an array of all matches of the full pattern,
  // and index 1 is an array of all captured links
  foreach ($matches[1] as $link) {

    // parse the link
    if ($parsed_link = parse_url($link)) {

      // see the documentation of parse_url() for the various
      // array keys produced by calling it; in this case we
      // are using the value of 'query' and passing it to
      // parse_str() which will break a url query string
      // into individual variables; pass $arguments as below
      // and it will populate the result into it as an array
      parse_str($parsed_link['query'],$arguments);

      // now, we want the value of the 'newurl' query parameter
      // from the original url
      if (isset($arguments['newurl'])) {

        $new_url = $arguments['newurl'];

        // do whatever you want with $new_url

      }

    }

  }

}

这当然不是唯一的方法,但使用语言功能保持一致性和可读性有一定的价值。我没有在上面的正则表达式中添加太多/任何想法来查找链接,因此它不处理任何特殊情况。如果文档中的链接格式不正确,您可能需要修改该表达式以处理额外的空格,错误的引号等。

相关问题