2012-11-26 2 views
0

위키 피 디아의 추천 기사 링크가 모두 포함 된 웹 페이지가 있습니다. 제목, 설명 및 키워드를 모두 추출합니다. 하지만 웹 크롤러가 기사의 내용을 추출하기 시작하면 문제가 생깁니다. 데이터베이스의 필드 설명이 비어 있고 키워드에 "Array Array Array"가 표시됩니다.위키 백과에서 php 및 mysql으로 설명과 키워드를 추출합니다.

위키 피 디아 기사의 설명과 키워드를 어떻게 추출 할 수 있습니까?

웹 크롤러는 PHP와 MySQL 프로그래밍, 이것은 실제 코드입니다 : https://www.wikidata.org/wiki/Wikidata:Data_access

:

<?php 
error_reporting(E_ALL | E_STRICT); 
set_time_limit(0); 
$server_link = mysql_connect("localhost", "root", ""); 
if (!$server_link) { 
    die("Fall&oacute; la Conexi&oacute;n " . mysql_error()); 
} 
$db_selected = mysql_select_db("test", $server_link); 
if (!$db_selected) { 
    die("No se pudo seleccionar la Base de Datos " . mysql_error()); 
} 
@mysql_query("SET NAMES 'utf8'"); 
function storeLink($titulo, $descripcion, $url, $keywords) { 
    $query = "INSERT INTO webs (webTitulo, webDescripcion, weburl, webkeywords) VALUES ('$titulo', '$descripcion', '$url', '$keywords')"; 
    mysql_query($query) or die('Error, falló la inserción de datos'); 
} 
function extraer($url, $prof, $patron) { 
    $userAgent = 'Interredu'; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(("Accept-Language: es-es,en"))); 
    curl_setopt($ch, CURLOPT_FAILONERROR, true); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 2); 
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $html = curl_exec($ch); 
    // La salvo de Entrada, para que no se me corra en la entrada a la base de datos 
    saveUrl($url, $prof, $patron, $html); 
    // Mando error pero no corto porque si una url esta mal formada termina con la 
    // ejecucion 
    if (!$html) { 
     echo "<br />cURL error number:" . curl_errno($ch); 
     echo "<br />cURL error:" . curl_error($ch); 
    } 
    $dom = new DOMDocument(); 
    $dom->loadHTML($html); 
    $xpath = new DOMXPath($dom); 
    $hrefs = $xpath->evaluate("/html/body//a"); 
    for ($i = 0;$i < $hrefs->length;++$i) { 
     $href = $hrefs->item($i); 
     $url2 = $href->getAttribute('href'); 
     $var = strstr($url2, '#', true); 
     if ($var !== false) { 
      $url2 = $var; 
     } 
     // Me aseguro que este bajo nuestro sitio. 
     if (strpos($url2, $patron) === false) { 
      continue; 
     } 
     // Me aseguro que ya no este ingresada, para no iterar sobre ella misam 
     if ($url2 != $url && $url2 != '') { 
      // Se podria agregar un campo timestap para luego reescanera paginas 
      // que tuvieran una fecha menor. 
      // URL Unica para que falle y como es mysql poner INSERT INTO ...... ON DUPLICATE KEY ... en la funcion de guardado 
      $busqueda = mysql_query("SELECT weburl FROM webs WHERE weburl='$url2'"); 
      $cantidad = mysql_num_rows($busqueda); 
      if (150 >= $prof && 0 == $cantidad) { 
       extraer($url2, ++$prof, $patron); 
      } 
     } 
    } 
} 
function saveUrl($url, $prof, $patron, $html) { 
    $retorno = false; 
    $pos = strpos($url, $patron); 
    if ($prof >= 1) { 
     preg_match_all("(<title>(.*)<\/title>)siU", $html, $title); 
     $metas = get_meta_tags($url, 1); 
     $title = $title[1][0]; 
     $titulo = html_entity_decode($title, ENT_QUOTES, 'UTF-8'); 
     $descripcion = isset($metas["description"])?$metas["description"] : ''; 
     $keywords = isset($metas["keywords"])?$metas["keywords"] : ''; 
    if (empty($descripcion)){ 
obtenerMetaDescription($html); 
    } 
    if (empty($keywords)){ 
    preg_match_all("#<\s*h1[^>]*>[^<]+</h1>#is", $html, $encabezado); 
    preg_match_all("#<\s*b[^>]*>[^<]+</b>#is", $html, $negrita); 
    preg_match_all("#<\s*i[^>]*>[^<]+</i>#is", $html, $italica); 
    if(!empty($encabezado)){ 
    $h1 = $encabezado[0]; 
    } 
    if(!empty($negrita)){ 
    $bold = $negrita[0]; 
    } 
    if(!empty($italica)){ 
    $italic = $italica[0]; 
    } 
    $keys .= $bold; 
    $keys .= " "; 
    $keys .= $h1; 
    $keys .= " "; 
    $keys .= $italic; 
    $keywords = substr(strip_tags($keys), 0, 200); 
} 
     storeLink($titulo, $descripcion, $url, $keywords, $prof); 
     $retorno = true; 
    } 
    return $retorno; 
} 
function obtenerMetaDescription($html) { 
    preg_match_all('#<p>(.*)</p>#Us', $html, $parraf); 
    if(!empty($parraf)){ 
    $descripcion = substr(strip_tags($parraf[1][0]), 0, 200); 
    } 
    } 
$url = "http://www.mywebsite.with.articlesofwikipedia"; 
$patron = "http://es.wikipedia.org/wiki/"; 
$prof = 150; 
libxml_use_internal_errors(true); 
extraer($url, 1, $patron); 
$errores = libxml_get_errors(); 
libxml_clear_errors(); 
mysql_close(); 
?> 
+2

db에 리터럴 텍스트로'Array'가 있으면 문자열 대신 somwhere 배열을 사용하고 있습니다. 예 : '$ x = array ('hello'); echo $ x'는'hello'가 아니라'Array'를 출력합니다. –

+2

dbpedia를 보길 원할 것입니다. – lynks

+0

답장을 보내 주셔서 감사합니다. 그러나 나는 어떤 배열을 보지 않는다. 설명을 복구하는 방법은 무엇입니까 ?? 답장을 보내 주셔서 감사합니다. –

답변

0

위키 백과에서 구조화 된 데이터에 대한 위키 데이터를 사용, 펑키 스크린 스크래핑 및 정규 표현식을 포기 MediaWiki API에는 여러 PHP 라이브러리가 있습니다. https://www.mediawiki.org/wiki/API:Client_code#PHP

appropriate badge에 대해 쿼리해야하는 기능 기사를 찾으려면 descr 항목에서 간단한 설명을 얻을 수 있습니다. iption 및 기타 정보를 제공합니다.

관련 문제