【问题标题】:How to scrape content betweeen all link tags like <a href="">SCRAPE THIS</a> on a page?如何在页面上的 <a href="">SCRAPE THIS</a> 等所有链接标签之间抓取内容?
【发布时间】:2012-08-23 20:33:56
【问题描述】:

我正在尝试抓取网站的链接文本,即 SCRAPE THIS。我想对页面上的所有链接执行此操作。到目前为止,我有这个:

<?php

$target_url = "SITE I WANT TO SCRAPE";

// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}

// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a/text()");

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    echo "<br />Link stored: $href";
}
?>

我对这些东西很陌生,不知道我做错了什么?

谢谢!

【问题讨论】:

  • 这会给你什么输出,哪里错了?
  • 不要冒充谷歌机器人怎么样。
  • 抱歉,刚刚在论坛上找到了该脚本并尝试了它。只是得到一个空白屏幕。正如我所说,我对这一切都是新手。我的错。
  • @MrBassam:RegEx 是解析 HTML 的错误工具。 stackoverflow.com/a/1732454\
  • @Rocket 谢谢你,我会改变主意的,谢谢你 :)

标签: php xpath screen-scraping


【解决方案1】:

在您的 for 循环中,$href 不是字符串。它实际上是一个 DOMText 节点。为了将其用作字符串,您需要访问其nodeValue 属性。

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    echo "<br />Link stored: $href->nodeValue";
}

【讨论】:

    【解决方案2】:

    试试:

    $xpath = new DOMXPath($dom);
    $hrefs = $xpath->evaluate("/html/body//a/text()");
    
    for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i)->textContent;
        echo "<br />Link stored: $href";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-09
      • 2017-02-09
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2017-08-30
      • 2011-09-27
      • 2018-04-09
      相关资源
      最近更新 更多