2014-01-07 3 views
0

저는 데이터베이스에 몇 가지 요소를 삽입하고 싶지만, $ pavadinimas와 % kaina는 한 줄에 있어야합니다. 게다가 웹 사이트의 모든 페이지에서 내 요소를 생성 할 수 있다면 꽤 멋지 겠지만 2 개 이상의 링크를 삽입하면 페이지를로드 할 수없는 웹을 새로 고침하는 데 오류가 발생합니다. 여기 내 코드가있다. 도와 주셔서 감사합니다!간단한 DOM 파서를 데이터베이스에 삽입하십시오.

<?php // example of how to modify HTML contents 


include_once('simple_html_dom.php'); 

// Create DOM from URL or file 

$html = file_get_html('https://www.varle.lt/mobilieji-telefonai/'); 

foreach($html->find('span[class=inner]') as $pavadinimas) { 
    $pavadinimas = str_replace("<span class=", " ", $pavadinimas); 
    $pavadinimas = str_replace("inner>", " ", $pavadinimas); 
    $pavadinimas = str_replace("<span>", " ", $pavadinimas); 
    $pavadinimas = str_replace("</span></span>", " ", $pavadinimas); 
    $pavadinimas = str_replace('"inner"> ', " ", $pavadinimas); 
} 

foreach($html->find('span[class=price]') as $kaina) { 
    $kaina = str_replace("Lt", " ", $kaina); 
    $kaina = str_replace("<span class=", " ", $kaina); 
    $kaina = str_replace("price", " ", $kaina); 
    $kaina = str_replace("</span>", " ", $kaina); 
    $kaina = str_replace(",<sup>99</sup>", " ", $kaina); 
    $kaina = str_replace(",<sup>99</sup>", " ", $kaina); 
    $kaina = str_replace("    ", " ", $kaina); 
    $kaina = str_replace('" ">', " ", $kaina); 
    $kaina = str_replace("    ", " ", $kaina); 
    $query = "insert into telefonai (pavadinimas,kaina) VALUES (?,?)"; 
    $this->db->query($query, array($pavadinimas,$kaina)); 
} 
?> 
+0

질문에 더 많은 태그를 사용할 수 있습니다. 어쩌면 PHP 예제도 있습니다. 그렇게하면 더 많은 사람들이 그것을 읽고 도움을 줄 수 있습니다. – Gonzalo

+0

'str_replace'를 쓰는 것은'$ pavadinimas-> plaintext'를 사용하여 쉽게 태그의 내용을 얻을 수 있기 때문에 시간 낭비입니다 ... [Manual] (http://simplehtmldom.sourceforge.net/manual. htm) 자세한 내용은 ... [답변 게시] – Enissay

답변

0

한 페이지 (예 : 1)에서 모든 원하는 정보를 얻어서 ...

시작을 단계적으로 진행 ... 생각은하는 것입니다

  • 모든 가져 오기 전화 블록 : 루프에서 $phones = $html->find('a[data-id]');
  • 는, (내가 잠시, BU 하나를 사용 didnt는 이후이 DB에 도움이 어차피 DB에 이러한 정보를 삽입 각 블록
  • 에서 원하는 정보 (이름, 가격)을 얻을

    • 모든 페이지를 : 당신이 당신의 자신의에서이 작업을 수행 할 수 있습니다 티셔츠는 이제 하나 개의 페이지에 대한 작동 코드를 가지고) 그 하드

    을 아니에요,의는 것을 알고는 모든 페이지에 작동하도록 해보자 동일한 구조를 가지고, 그래서 우리는

  • Next 버튼에 포함되어 긁어 다음 페이지의 링크를 위와 같은 방법/코드와 데이터를 추출 할 수 있습니다, 그래서 우리는이 링크를 찾을 수없는 경우에 중단됩니다

그래서 h 오히려 우리가 위에 말한 모든 요약 한 코드입니다 :

$url = "https://www.varle.lt/mobilieji-telefonai/"; 

// Start from the main page 
$nextLink = $url; 

// Loop on each next Link as long as it exsists 
while ($nextLink) { 
    echo "<hr>nextLink: $nextLink<br>"; 
    //Create a DOM object 
    $html = new simple_html_dom(); 
    // Load HTML from a url 
    $html->load_file($nextLink); 

    ///////////////////////////////////////////////////////////// 
    /// Get phone blocks and extract info (also insert to db) /// 
    ///////////////////////////////////////////////////////////// 
    $phones = $html->find('a[data-id]'); 

    foreach($phones as $phone) { 
     // Get the link 
     $linkas = $phone->href; 

     // Get the name 
     $pavadinimas = $phone->find('span[class=inner]', 0)->plaintext; 

     // Get the name price and extract the useful part using regex 
     $kaina = $phone->find('span[class=price]', 0)->plaintext; 
     // This captures the integer part of decimal numbers: In "123,45" will capture "123"... Use @([\d,]+),[email protected] to capture the decimal part too 
     preg_match('@(\d+),[email protected]', $kaina, $matches); 
     $kaina = $matches[1]; 

     echo $pavadinimas, " #----# ", $kaina, " #----# ", $linkas, "<br>"; 

     // INSERT INTO DB HERE 
     // CODE 
     // ... 
    } 
    ///////////////////////////////////////////////////////////// 
    ///////////////////////////////////////////////////////////// 

    // Extract the next link, if not found return NULL 
    $nextLink = (($temp = $html->find('div.pagination a[class="next"]', 0)) ? "https://www.varle.lt".$temp->href : NULL); 

    // Clear DOM object 
    $html->clear(); 
    unset($html); 
} 

출력

nextLink: https://www.varle.lt/mobilieji-telefonai/ 
Samsung Phone I9300 Galaxy SIII Juodas #----# 1099 #----# https://www.varle.lt/mobilieji-telefonai/samsung-phone-i9300-galaxy-siii-juodas.html 
Samsung Galaxy S2 Plus I9105 Pilkai mėlynas #----# 739 #----# https://www.varle.lt/mobilieji-telefonai/samsung-galaxy-s2-plus-i9105-pilkai-melynas.html 
Samsung Phone S7562 Galaxy S Duos baltas #----# 555 #----# https://www.varle.lt/mobilieji-telefonai/samsung-phone-s7562-galaxy-s-duos-baltas--457135.html 
... 

nextLink: https://www.varle.lt/mobilieji-telefonai/?p=2 
LG T375 Mobile Phone Black #----# 218 #----# https://www.varle.lt/mobilieji-telefonai/lg-t375-mobile-phone-black.html 
Samsung S6802 Galaxy Ace Duos black #----# 579 #----# https://www.varle.lt/mobilieji-telefonai/samsung-s6802-galaxy-ace-duos-black.html 
Mobilus telefonas Samsung Galaxy Ace Onyx Black | S5830 #----# 559 #----# https://www.varle.lt/mobilieji-telefonai/mobilus-telefonas-samsung-galaxy-ace-onyx-black.html 
... 

... 
... 

Working DEMO

주의 코드가 모든 페이지를 구문 분석하는 데 시간이 걸릴 수 있음을가, 그래서 PHP는이 오류 Fatal error: Maximum execution time of 30 seconds exceeded ...을 반환 할 수 있습니다. 그런 다음 최대 실행 시간을 다음과 같이 확장하면됩니다.

ini_set('max_execution_time', 300); //300 seconds = 5 minutes 
+0

정말 고맙게도 대답 해 주셔서 감사합니다. – Mangirdas

+0

@ user3125624, 안녕하세요. 문제가 해결 되었다면 대답을 승인 된 것으로 표시하십시오. – Enissay