嗨,下面是我的代码,它没有提供预期的结果。
首先,它应该使用cURL
然后使用正则表达式提供页面的完整 html 内容,当我直接htmlcontent
提供它们时,正则表达式会提供预期的结果,但使用 curl 不提供相同的结果。
假设当我将以下内容传递给htmlcontent
变量时,RegExp
提供正确的结果。
$htmlContent = '<table id="ctl00_pageContent_ctl00_productList" class="product-list" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;">
<tr>
<td class="product-list-item-container" style="width:100%;">
<div class="product-list-item" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'ctl00_pageContent_ctl00_productList_ctl00_imbAdd')">
<a href="/W10542314D/WDoorGasketandLatchSt.aspx">
<img class="product-list-img" src="/images/products/display/applianceparts.jpg" title="W10542314 D/W Door Gasket & Latch St " alt="W10542314 D/W Door Gasket & Latch St " border="0" />
</a>
<div class="product-list-options">
<h5><a href="/W10542314D/WDoorGasketandLatchSt.aspx">W10542314 D/W Door Gasket & Latch St</a></h5>
<div class="product-list-cost"><span class="product-list-cost-label">Online Price:</span> <span class="product-list-cost-value">$33.42</span></div>
</div>
';
以下是我的完整代码 -
<?php
$url = "http://www.universalapplianceparts.com/search.aspx?find=W10130694";
$ch1= curl_init();
curl_setopt ($ch1, CURLOPT_URL, $url );
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1,CURLOPT_VERBOSE,1);
curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
curl_setopt ($ch1, CURLOPT_REFERER,'http://www.google.com'); //just a fake referer
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1,CURLOPT_POST,0);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 20);
$htmlContent= curl_exec($ch1);
echo $htmlContent;
$value=preg_match_all('/.*<div.*class='"product'-list'-options'".*>.*<a href="(.*)">.*<'/a>.*<'/div>/s',$htmlContent,$matches);
print_r($matches);
$value=preg_match_all('/.*<div.*class='"product'-list'-item'".*>.*<a href='"(.*)'">.*<img.*>.*<'/div>/s',$htmlContent,$matches);
print_r($matches);
在此代码中,它回显网页的html内容,然后使用正则表达式,它应该返回div之间的锚标记href
,该类名product-list-options
和product-list-item
电流输出为 -
http://www.universalapplianceparts.com/termsofservice.aspx
在这里,正则表达式以相反的顺序从 cURL 读取我的 html 内容,并在锚标记中返回第一个 href 值。
数组值中的预期输出 - /W10130694LatchAssyWhiteHandle.aspx
任何帮助将不胜感激。
谢谢
试试这个
class="product-list-item".*?<a href="(.*?)".*?class="product-list-options"
演示
输出
MATCH 1
1. [23040-23075] `/W10130694LatchAssyWhiteHandle.aspx`
解释:
class="product-list-item"
比赛class="product-list-item"
.*?
尽可能少地
匹配任何字符 <a href="
匹配<a href="
href="(.*?)"
捕获href=""
中的文本 class="product-list-options"
匹配class="product-list-options"