我想提取具有属性名称的页面的内容 itemprop
.假设我的页面具有不同的HTML标签,这些标签具有名为itemprop
的属性,因此我希望这些标签之间的文本,
对于标题:
<h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>
来自 td 标签的表数据:
<td itemprop="productID">AP3963893</td>
这里的itemprop
属性是常见的。所以我需要这些标签之间的数据,例如使用 regexp 的 Whirlpool Direct Drive Washer Motor Coupling
和 AP3963893
.
下面是我的代码(目前不起作用)
preg_match_all(
'/<div class='"pdct'-inf'">(.*?)<'/div>/s',
$producturl,
$posts
);
我的代码:
<?php
define('CSV_PATH','csvfiles/');
$csv_file = CSV_PATH . "producturl.csv"; // Name of your producturl file
$csvfile = fopen($csv_file, 'r');
$csv_fileoutput = CSV_PATH . "productscraping.csv"; // Name of your product page data file
$csvfileoutput = fopen($csv_fileoutput, 'a');
$websitename = "http://www.appliancepartspros.com";
while($data = fgetcsv($csvfile))
{
$producturl = $websitename . trim($data[1]);
preg_match_all(
'/<.*itemprop='".*'".*>(.*?)<'/.*>/s',
$producturl,
$posts
);
print_r($posts);
}
首先,永远不要使用正则表达式来解析 HTML。其次,你可以通过使用属性选择器非常简单地使用 jQuery 来实现这一点:
var nameItemprop = $('[itemprop="name"]').text(); // = 'Whirlpool Direct Drive Washer Motor Coupling'
var productIdItemprop = $('[itemprop="productID"]').text(); // = 'AP3963893'
但请注意,创建自己的非标准属性是无效的 HTML。理想情况下,您应该使用 data-*
属性来包含与这些元素关联的数据:
<h1 data-itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>
<td data-itemprop="productID">AP3963893</td>
var nameItemprop = $('[data-itemprop="name"]').text();
var productIdItemprop = $('[data-itemprop="productID"]').text();
最后,如果有多个元素具有相同的itemprop
属性,则需要遍历它们以从每个单独的元素中获取值。
如前所述,您不应该使用 RegExp 来解析 HTML,但如果您坚持这样做,这里有一个应该有效的模式:
$producturl = '<h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>';
if (preg_match_all(
'/<.*itemprop='".*'".*>(.*?)<'/.*>/s',
$producturl,
$posts
)) {
print_r($posts);
}
这将创建以下输出:
Array
(
[0] => Array
(
[0] => <h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>
)
[1] => Array
(
[0] => Whirlpool Direct Drive Washer Motor Coupling
)
)