【问题标题】:PHP - Multi Curl - scraping for data/contentPHP - 多卷曲 - 抓取数据/内容
【发布时间】:2012-09-08 02:31:29
【问题描述】:

我已经开始使用 curl、dom、xpath 构建单个 Curl 会话,并且效果很好。

我现在正在构建一个基于 curl 的刮板,用于在一个流程中从多个站点中获取数据,并且脚本正在回显我输入的单个短语.. 但它不会拾取变量。

do{
    $n=curl_multi_exec($mh, $active);
}while ($active);

foreach ($urls as $i => $url){  
    $res[$i]=curl_multi_getcontent($conn[$i]);      
    echo ('<br />success');
}

所以这确实会像有 url 一样多次回显成功文本.. 但实际上这不是我想要的.. 我想像使用单个 curl 会话一样分解 html..

我在单次 curl 会话中做了什么:

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

// grab all the on the page
$xpath = new DOMXPath($dom);         
$product_img = $xpath->query("//div[@id='MAIN']//a");

for ($i = 0; i < $product_img->length; $i++){
    $href = $product_img->item($i);
    $url = $href->getAttribute('href');
    echo "<br />Link : $url";
}

这个 dom 解析/xpath 对单会话 curl 有效,但在我运行 multicurl 时无效。 在 Multicurl 上,我可以为会话中的 URL 执行 curl_multi_getcontent,但这是不想要的。 我想获得与我在单个会话中使用 Dom / Xpath 获得的相同内容。 我能做什么?

编辑

看来我的 getAttribute 有问题。这是我无法抓取的图像的链接。抓取时会显示链接,但随后会引发错误:

致命错误:在非对象中调用成员函数 getAttribute()

查询:

// grab all the on the page
$xpath = new DOMXPath($dom);
$product_img = $xpath->query("//img[@class='product']");
$product_name = $xpath->query("//img[@class='product']");

这是有效的:

for ($i = 0; i < $product_name->length; $i++) {
    $prod_name = $product_name->item($i);
    $name = $prod_name->getAttribute('alt');
    echo "<br />Link stored:  $name";
}

这不起作用:

for ($i = 0; i < $product_img->length; $i++) {
    $href = $product_img->item($i);
    $pic_link = $href->getAttribute('src');
    echo "<br />Link stored:  $pic_link";
}

知道我做错了什么吗? 提前致谢。

【问题讨论】:

  • 欢迎来到 SO!为了帮助我们更容易阅读问题,请正确格式化代码。
  • 你好,查尔斯。感谢您的帮助!

标签: php dom xpath curl web-scraping


【解决方案1】:

出于某种奇怪的原因,只有一个 src 无法正常工作。
这个问题可以认为是“已解决”。

【讨论】:

  • 出于某种奇怪的原因,只有一个'src'不能正常工作。所以这可以被认为是“解决”。 /尼尔斯
猜你喜欢
  • 2013-07-05
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
  • 2016-11-24
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多