【问题标题】:PHP curl web scraper - scraping specific divPHP curl web scraper - 抓取特定的div
【发布时间】:2015-10-22 21:14:53
【问题描述】:

我需要从这个网站上抓取带有价格的产品列表。

我需要添加什么才能仅在此产品列表中添加内容 (http://www.tehnomanija.rs/lcd-i-led--televizori)

这是我的代码:

<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://www.tehnomanija.rs/lcd-i-led--televizori");
curl_exec ($curl);

$result = curl_exec($curl);
curl_close ($curl);

//parser
preg_match("<td class=\"product_list_cell\">")siU, $result, $matches1);


$suscriptores = $matches1[1][0];
echo "Suscriptores: " . $suscriptores;
print $result;

?>

【问题讨论】:

  • 你可以使用任何 html 解析器(比如 simple_html_dom 左右)

标签: php curl web-scraping


【解决方案1】:

看看https://github.com/tj/php-selector
它本质上是 DOMDocumentDOMxpath 的包装器,允许您像这样使用 css 选择器

$elements = select_elements('div#someId', $html);

【讨论】:

    【解决方案2】:

    您在此任务中使用正则表达式是错误的。使用 xpath 从 html 中检索所需的 dom 节点。见an example

    我也可能会提到你的一些错误:

    1. 您没有在 curl 中包含 RETURN_TRANSFERdocs
    2. 您没有通过正则表达式正确获取,docs

    所以代码应该是这样的:

    <?php
    $curl = curl_init();
    curl_setopt ($curl, CURLOPT_URL, "http://www.tehnomanija.rs/lcd-i-led--televizori");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
    $result = curl_exec($curl);
    curl_close ($curl);
    
    //parser
    preg_match("/<td\s+class=\"product_list_cell\">(.*?)<\/td>/siU", $result, $matches);
    print_r($matches[1]);
    
    $suscriptores = $matches[1];
    echo "Suscriptores: " . $suscriptores;
    print $result;
    

    然而,由于内部结构混合了不同级别的&lt;/td&gt;s,您仍然无法正确地通过正则表达式获取。您唯一的方法是 xPath。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多