【问题标题】:Website Scraping Using PHP使用 PHP 进行网站抓取
【发布时间】:2014-10-16 06:06:19
【问题描述】:

我有一个可以提取本网站产品类别的 php 代码:http://www.tradeindia.com/。到目前为止,我已经设法只提取了类别。我如何制作它以便它也可以提取它旁边的产品编号,因为它不在任何类名中?

我的代码:

<?php 
//header('Content-Type: text/html; charset=utf-8'); 
$grep = new DoMDocument(); 
@$grep->loadHTMLFile("http://www.tradeindia.com/"); 
$finder = new DomXPath($grep); 
$class = "cate_menu"; 
$nodes = $finder->query("//*[contains(@class, '$class')]"); 

$total_L = 0; 
foreach ($nodes as $node) { 
$span = $node->childNodes; 
echo '<br>' . $span->item(0)->nodeValue . ' : '; 
} 

?> 

来自网站的源代码:

<td align="left" style="padding-left:8px;color:blue"><a href=/Seller/Agriculture/ class="cate_menu" >Agriculture</a>(100892)</td>
<td align="left" style="padding-left:8px;color:blue"><a href=/Seller/Apparel-Fashion/ class="cate_menu" >Apparel & Fashion</a>(237902)</td>
<td align="left" style="padding-left:8px;color:blue"><a href=/Seller/Automobile/ class="cate_menu" >Automobile</a>(78614)</td>

我需要括号内的数字。

【问题讨论】:

  • regex 在这种情况下会很好地完成这项工作。
  • 如果可能的话我想用这种方式(domdocument)
  • 你好,cael,你到底要刮哪些产品?特色产品?
  • 顶部类别中的产品数量。我有类别列表(农业、服装和时尚),但我无法获得它旁边的数字(减去括号)。

标签: php html xpath web-scraping domdocument


【解决方案1】:

我不是 xpath 专家,但我要做的是首先使用针类别定位特定表,然后从那里获取基于该类别的行并开始在找到的行上循环。

粗略的例子:

$grep = new DOMDocument();
@$grep->loadHTMLFile("http://www.tradeindia.com/");
$finder = new DOMXpath($grep);

$products = array();
$nodes = $finder->query("
    //td[@class='showroom1'][contains(text(), 'CATEGORIES')]
    /parent::tr/parent::table/parent::td/parent::tr
    /following-sibling::tr
    /td[1]/table/tr/td/table/tr
");

if($nodes->length > 0) {
    foreach($nodes as $tr) {
        if($finder->evaluate('count(./td/a)', $tr) > 0) {
            foreach($finder->query('./td/a[@class="cate_menu"]', $tr) as $row) {
                $text = $row->nodeValue;
                $number = $finder->query('./following-sibling::text()', $row)->item(0)->nodeValue;
                $products[] = "$text $number";
            }

        }
    }
}

echo '<pre>';
print_r($products);

Sample Output

【讨论】:

  • 谢谢,我试过了,但似乎只能提取第一列。有没有办法得到剩下的 2 列?
  • @Cael 再次检查我的修订,现在正确
  • 感谢您的大力帮助 :)
【解决方案2】:

由于数字在两个括号之间,这应该很容易。你可以使用这样的函数;

function get_string_between($string, $start, $end) {
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);   
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}

$product = get_string_between($htmlline, "(", ")");

您需要单独插入表格的每一行。您可以遍历包含每一行的字符串数组; foreach($htmllines as $htmlline) 或类似的。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 2010-12-28
    • 1970-01-01
    • 2018-10-17
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多