【发布时间】:2010-08-21 13:21:12
【问题描述】:
使用 PHP 解析 HTML / JS 代码以获取信息。
www.asos.com/Asos/Little-Asos-Union-Jack-T-Shirt/Prod/pgeproduct.aspx?iid=1273626
看看这个页面,这是一家儿童服装店。这是他们的项目之一,我想指出尺寸部分。我们在这里需要做的是获取该项目的所有尺寸并检查尺寸是否可用。目前该商品的所有尺寸为:
3-4 years
4-5 years
5-6 years
7-8 years
你怎么知道尺寸是否可用?
现在先看看这个页面,然后再检查一下尺寸:
www.asos.com/Ralph-Lauren/Ralph-Lauren-Long-Sleeve-Big-Horse-Stripe-Rugby-Top/Prod/pgeproduct.aspx?iid=1111751
此商品有以下尺寸:
12 months
18 months - Not Available
24 months
您可以看到 18 个月的尺码不可用,它由尺码旁边的“不可用”文本指示。
我们需要做的是转到一个项目的页面,获取尺寸并检查每个尺寸的可用性。如何在 PHP 中做到这一点?
编辑:
添加了一个工作代码和一个要解决的新问题。
工作代码,但需要更多工作:
<?php
function getProductVariations($url) {
//Use CURL to get the raw HTML for the page
$ch = curl_init();
curl_setopt_array($ch,
array(
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_HEADER => false,
CURLOPT_URL => $url
)
);
$raw_html = curl_exec($ch);
//If we get an invalid response back from the server fail
if ($raw_html===false) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
//Find the variation JS declarations and extract them
$raw_variations = preg_match_all("/arrSzeCol_ctl00_ContentMainPage_ctlSeparateProduct\[[0-9]+\].*Array\((.*)\);/",$raw_html,$raw_matches);
//We are done with the Raw HTML now
unset($raw_html);
//Check that we got some results back
if (is_array($raw_matches) && isset($raw_matches[1]) && sizeof($raw_matches[1])==$raw_variations && $raw_variations>0) {
//This is where the matches will go
$matches = array();
//Go through the results of the bracketed expression and convert them to a PHP assoc array
foreach($raw_matches[1] as $match) {
//As they are declared in javascript we can use json_decode to process them nicely, they just need wrapping
$proc=json_decode("[$match]");
//Label the fields as best we can
$proc2=array(
"variation_id"=>$proc[0],
"size_desc"=>$proc[1],
"colour_desc"=>$proc[2],
"available"=>(trim(strtolower($proc[3]))=="true"),
"unknown_col1"=>$proc[4],
"price"=>$proc[5],
"unknown_col2"=>$proc[6], /*Always seems to be zero*/
"currency"=>$proc[7],
"unknown_col3"=>$proc[8],
"unknown_col4"=>$proc[9], /*Negative price*/
"unknown_col5"=>$proc[10], /*Always seems to be zero*/
"unknown_col6"=>$proc[11] /*Always seems to be zero*/
);
//Push the processed variation onto the results array
$matches[$proc[0]]=$proc2;
//We are done with our proc2 array now (proc will be unset by the foreach loop)
unset($proc2);
}
//Return the matches we have found
return $matches;
} else {
throw new Exception("Unable to find any product variations");
}
}
//EXAMPLE USAGE
try {
$variations = getProductVariations("http://www.asos.com/Asos/Prod/pgeproduct.aspx?iid=803846");
//Do something more useful here
print_r($variations);
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
上面的代码有效,但是当产品需要您在显示尺寸之前先选择颜色时,就会出现问题。
喜欢这个:
知道该怎么做吗?
【问题讨论】:
-
我刚刚发现选择大小的选项是由 AJAX 填充的。如您所见,这是尺寸选择 DIV。填充此 DIV 的信息显然来自与后端脚本的 AJAX 交互。 “不可用”一词不在 HTML 中,但当您打开 SELECT 表单控件时,它们会清楚地呈现在屏幕上。所以它们以其他方式放入 DOM 中。 fopen 和 file_get_contents 在这里还能用吗?
标签: php html parsing html-parsing