【问题标题】:how to fetch flipkart product specification and feature如何获取 Flipkart 产品规格和功能
【发布时间】:2016-04-06 18:45:00
【问题描述】:

我正在尝试从 Flipkart 获取产品规格和功能列表。我正在使用以下代码,但无法获取规范。

有什么东西可以让我的代码完整。

<?php
$url = 'http://www.flipkart.com/samsung-415-l-frost-free-double-door-refrigerator/p/itmedp6zcppxvhgh?pid=RFREDP6ZJXFY5QMK&al=Xh6p4IpEIjAx6PWgfu6yt8ldugMWZuE7%2BW7da8XnwKRuC2TkVUlPYWLhfoM4PDZcEqn50nOHN48%3D&ref=L%3A1683055601844045008&srno=p_2&query=samsung+rt42&otracker=from-search';
$response = getPriceFromFlipkart($url);
echo json_encode($response);
/* Returns the response in JSON format */
function getPriceFromFlipkart($url) {

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_USERAGENT, "Chrome/49.0.2623.110 (Windows; U; Windows NT 10.10; labnol;) ctrlq.org");
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($curl);
curl_close($curl);    

$regex = '/<meta itemprop="price" content="([^"]*)"/';
preg_match($regex, $html, $price);

$regex = '/<h1[^>]*>([^<]*)<\/h1>/';
preg_match($regex, $html, $title);    

$regex = '/data-zoomimage="([^"]*)"/i';
preg_match($regex, $html, $image);

if ($price && $title && $image) {
    $response = array("price" => "Rs. $price[1].00", "image" => $image[1], "title" => $title[1], "status" => "200");
    
} else {
    $response = array("status" => "404", "error" => "We could not find the product details on Flipkart $url");
}
 
 return $response;
}
?>

【问题讨论】:

标签: php regex web-scraping preg-match


【解决方案1】:

没有神奇的正则表达式可以做到这一点。您可能需要混合使用多个正则表达式和代码来获得规范。

一个起点可以是使用&lt;div[^&gt;]*&gt;\s*Specifications\s*&lt;\/div&gt;(.*?)&lt;div[^&gt;]*&gt;\s*Questions\s*and\s*Answers

见:https://regex101.com/r/Tanr0H/4

这将获得从“规范”到“问题和答案”的 html 响应

请参阅懒惰与贪婪以了解 (.*?) 的工作原理:What do 'lazy' and 'greedy' mean in the context of regular expressions?

另外,使用一些库来解析 html 可能是个好主意

How do you parse and process HTML/XML in PHP?

【讨论】:

  • 另外,请记住,您必须使用 s 修饰符才能使 . 也匹配换行符
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 2013-11-23
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 2011-03-09
相关资源
最近更新 更多