簡體   English   中英

使用RegEx在HTML標簽之間查找內容

[英]Find content between HTML tags using RegEx

我想提取具有屬性名稱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 CouplingAP3963893

下面是我的代碼(目前不起作用)

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);
    }

首先, 永遠不要使用RegEx解析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
        )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM