[英]How do I access individual <span> for scraping web data in PHP?
我正在嘗試從幾個家得寶 URL 中獲取定價數據。 我正在使用 simple_html_dom.php,可以在這里找到: https ://simplehtmldom.sourceforge.io/
我在弄清楚如何獲取我需要的單個跨度類以獲取我想要的數據時遇到問題。
這是帶有我嘗試訪問的各個字段的檢查元素的圖像: https : //prnt.sc/qx5ujt
這是我到目前為止的代碼,它返回一個空數組:
?<php
require 'simple_html_dom.php';
$dom = file_get_html('https://www.homedepot.com/p/Zinsco-20-Amp-1-1-2-in-2-Pole-Replacement-Thick-Circuit-Breaker-UBIZ220/100183119', false);
$answer = array();
if(empty($dom))
{
echo "EMPTY";
exit;
}
$divClass = "";
$dollars = "";
$cents = "";
$i = 0;
foreach($dom->find('price__wrapper') as $divClass)
{
foreach($divClass->find('span[class=price__dollars]') as $dollars) //dollars
{
$answer[$i]['dollars'] = $dollars->plaintext;
}
foreach($divClass->find('span[class=price__cents]') as $cents) //cents
{
$answer[$i]['cents'] = $cents->plaintext;
}
$i++;
}
print_r($answer);
exit;
?>
如果 HTML 看起來總是像屏幕截圖中的那樣,那么您可以繼續使用父 span 元素的content
屬性。
您可以像下面這樣存檔(未經測試的示例)。
// Get the parent span element with ID ajaxPrice
$element = $dom->find('span#ajaxPrice',0);
// Check if attribute "content" exists
if(isset($element->content)) {
$price = $element->content; // This is the price as string value
$priceFloat = floatval($price); // This is the price as float value
// Splitting price in dollar and cent
$price = explode('.', $price);
$dollar = $price[0];
$cent = $price[1];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.