Foros del Web » Programando para Internet » Javascript »

Buscar en una página y mostrar el contenido

Estas en el tema de Buscar en una página y mostrar el contenido en el foro de Javascript en Foros del Web. Hola a todos. Probablemente este problema no sea tan problema, pero no sé cómo resolverlo, por favor que alguien me ayude. Necesito un código que ...
  #1 (permalink)  
Antiguo 20/12/2004, 20:26
 
Fecha de Ingreso: diciembre-2004
Mensajes: 2
Antigüedad: 19 años, 4 meses
Puntos: 0
Pregunta Buscar en una página y mostrar el contenido

Hola a todos. Probablemente este problema no sea tan problema, pero no sé cómo resolverlo, por favor que alguien me ayude. Necesito un código que permita tomar el valor de una entrada en un campo de texto y automáticamente me busque de entre un grupo de páginas un valor igual(digamos la palabra difícil del campo de texto, el script busca entre las páginas indicadas el texto difícil que aparece entre marcas de cualquier tipo, digamos div o h3, "captura" su valor y lo muestra en la página donde aparece el campo de texto)
Disculpen si este problema les resulta una pérdida de tiempo, pero mi fuerte no es el javascript de seguro.
Gracias de antemano por la ayuda.
  #2 (permalink)  
Antiguo 20/12/2004, 20:44
 
Fecha de Ingreso: enero-2003
Ubicación: Córdoba, Argentina
Mensajes: 1.047
Antigüedad: 21 años, 3 meses
Puntos: 10
desconosco que esto lo puedas solucionar con javascript... Pero sin duda seria mucho mejor que lo hicieras con algun lenguaje que se ejecute del lado del servidor (PHP, ASP, Etc..
__________________
oohh... quisiera ser godines!!!
  #3 (permalink)  
Antiguo 20/12/2004, 21:35
 
Fecha de Ingreso: diciembre-2003
Mensajes: 54
Antigüedad: 20 años, 4 meses
Puntos: 0
Como poder se puede. Primero necesitarias cargar el contenido de las paginas en las que quieras buscar(de a una) utilizando un iframe o xml http request y buscar en el innerText/nodos de texto la palabra. Obviamente este es un proceso poco eficiente ya que el usuario tiene que bajar todas las paginas cada vez que tiene que buscar algo.
Como dijo safe, lo mejor seria que hagas el procesamiento en el servidor y solamente muestres los resultados.

Link util: http://www.w3schools.com/

Saludos
  #4 (permalink)  
Antiguo 22/12/2004, 18:51
 
Fecha de Ingreso: diciembre-2004
Mensajes: 2
Antigüedad: 19 años, 4 meses
Puntos: 0
Gracias a ambos. Me olvidé decirles que lo que intento hacer es para una página web dentro de una intranet universitaria, y que tenemos un solo servidor, al cual por razones de seguridad no se puede acceder sino como cliente. Pero de todos modos es válida la aclaración. tendré que instalar el php en la máquina y hacer que lo que quiero funcione como una base de datos. Aunque me proponía hacer algo más sencillo, así creía yo al menos. Por ejemplo, acceder a una página cualquiera de un grupo determinado y reducido de páginas y capturar los datos empleando getElementById(elemento).innerhtml.value o algo así, y presentarlos a los usuarios de esa forma. Lo que quiero exactamente es un minidiccionario de términos cubanos en inglés para estudiantes, lo cual no aparece en los diccionarios. Si se les ocurriera algo, háganmelo saber, sino tendré que conformarme con el php. Gracias y feliz fin de año y año nuevo para ambos y sus seres queridos. Chao desde Cuba.
  #5 (permalink)  
Antiguo 23/12/2004, 11:07
 
Fecha de Ingreso: abril-2004
Mensajes: 84
Antigüedad: 20 años
Puntos: 0
Puedes usar un applet java para eso, hay muchos y muy variados, como el site seracher, etc...
  #6 (permalink)  
Antiguo 23/12/2004, 18:10
 
Fecha de Ingreso: enero-2003
Ubicación: Córdoba, Argentina
Mensajes: 1.047
Antigüedad: 21 años, 3 meses
Puntos: 10
si en lo que tenes que buscar no es muy mucho lo que podes hacer es poner el contenido de cada pagina en un array y hacer la busqueda en el array... te paso una pequeña modificacion de un script que saque de este post:

http://forosdelweb.com/showthread.php?t=137228


Código PHP:
<html>
<
head>
<
script language="javascript" type="text/javascript">

function 
buscador(palabra){
    var 
cadena = new Array();
    
cadena[0] = new Array("Chocolate con crema de naranja""pagina 1""01.htm");
    
cadena[1] = new Array("Azucar impalpable""pagina 2""02.htm");
    
cadena[2] = new Array("Mouse de Limon""pagina 3""03.htm");
    
cadena[3] = new Array("Pomelo Chocolate a la naranja""pagina 4""04.htm");
    
// donde es -> new Array("CONTENIDO", "TITULO", "PAGINA");
    
    
var resultado = new Array();
    var 
0
    
var 0
    
var tot cadena.length-1;
    var 
buscar palabra
    
while (<= tot) {
        var 
patron = new RegExp(buscar,"gi");
        var 
resul patron.test(cadena[c]);
        if (
resul == true) {
            
resultado[a]=new Array("Se encontro "+buscar+" en "+cadena[c][1],cadena[c][2]);
            
a=a+1;
        }
        
c=c+1;
    }
    
document.getElementById("celda").innerHTML "Se han encontrado "+a+" concordancias<br>";
    var 
0
    
var tot resultado.length-1;
    while (
<= tot) {
        
document.getElementById("celda").innerHTML document.getElementById("celda").innerHTML "<br><a href='"+resultado[c][1]+"'>"+resultado[c][0]+"</a>";
        
c=c+1;
    }
}

</script>
</head>
<body>
<input type="text" id="buscar" name="buscar">
<input type="button" value="buscar" onClick="javascript: buscador(document.getElementById('buscar').value);">
<table><tr><td id="celda">&nbsp;</td></tr></table>
</body>
</html> 
__________________
oohh... quisiera ser godines!!!
  #7 (permalink)  
Antiguo 24/12/2004, 04:56
 
Fecha de Ingreso: diciembre-2004
Mensajes: 15
Antigüedad: 19 años, 4 meses
Puntos: 0
Hola, a ver si te sirve de ayuda esto, lo saque de otro foro, el único inconveniente es que está ASP, pero lo mismo te ayuda.

Dos paginas, una HTML y otra ASP

HTML:
Código:
<table cellspacing=2 cellpadding=2 border=0>
<tbody> 
<tr valign=bottom align=middle> 
<td bgcolor="#8CA6CE"><font color="#FFFFFF"><b><font size="2" face="Arial, Helvetica, sans-serif">SEARCH</font></b></font></td>
</tr>
<tr valign=top align=middle> 
<td> 
<table cellspacing=0 cellpadding=1 width=171 
border=0 bgcolor=#8CA6CE>
<tbody> 
<tr> 
<td width="100%"> <font face="verdana, arial, helvetica" 
size=-1><small> </small></font> 
<table cellspacing=0 cellpadding=4 width="100%" 
bgcolor=#8CA6CE border=0>
<tbody> 
<tr> 
<!-- 
The chuck of code generates the search box. Every page that has a search box needs it. 
//-->
<form action="search.asp" method="post">
<td align=left bgcolor="#FFFFFF"> 
<input class=formcreate type=text 
name=txtKeyWord size="10">
<input class=formcreate type=submit value="GO" name=search>
</td>
</form>
<!--
End of the search form
//-->
</tr>
</tbody> 
</table>
</td>
</tr>
</tbody> 
</table>
</td>
</tr>
</tbody> 
</table>
ASP:
Código:
<%@ Language=VBScript %>

<%

Option Explicit
Response.Buffer = True

' Set up some FileSystem objects.
dim objFS, objFolder, objFiles, File, FileName, objCheckFile, strSitePath
set objFS = server.CreateObject("Scripting.FileSystemObject")

dim strListofFiles, arrFileList, strPageTitle, iReturnCount
dim objFolders

strListofFiles = ""
iReturnCount = 0

' The search values, search space, and the return value
dim strKeyWord, strFileContents, returnValue, arrKeyWords
dim bKeyWordFound, i, j

' Get the Physical path to the current directory
strSitePath = Server.MapPath(".")

' Grab the keyworlds and split them into an array
strKeyWord = Trim(request("txtKeyWord"))
arrKeyWords = split(strKeyWord," ")

' Get the list of files.
Set objFolder = objFS.GetFolder(strSitePath)


' Sub that grabs all the ".htm" & ".html" files in the given folder and
' recurses through all subfolders. 
sub getCompleteFileList(inFolder, Path)

dim oFiles, oFolders, Folder, sPath

' Get all the files and subfolders.
Set oFiles = inFolder.Files
Set oFolders = inFolder.SubFolders

' If we have a subfolder we need the partial path
if (Path <> "") then
sPath = Path + "\"
end if

' Add each ".htm" & ".html" file to the list
For Each File in oFiles
FileName = File.Name

if((Lcase(right(FileName,4)) = ".htm") OR (Lcase(right(FileName,5)) = ".html")) then
if (strListofFiles = "") then
strListofFiles = sPath + FileName
else 
strListofFiles = strListofFiles + "," + sPath + FileName
end if 
end if
Next

' Check all the subfolders for ".htm" & ".html" files
For Each Folder in oFolders
if (Folder.Name <> "images" AND Folder.Name <> "stats") then 
call getCompleteFileList(Folder, sPath + Folder.Name)
end if
Next

' Clean up 
set File = Nothing
set oFiles = Nothing
set Folder = Nothing
set oFolders = Nothing

end sub

%>
<html>
<head>
<title>Search </title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF" text="#000000">
<table cellspacing=7 cellpadding=2 border=0 width="100%">
<tbody> 
<tr> 
<td valign=top align=middle> 
<table cellspacing=0 width="100%" border=0>
<tbody> 
<tr> 
<td align=middle bgcolor=#3366cc> 
<table cellspacing=0 cellpadding=2 width="100%" border=0>
<tbody> 
<tr> 
<td align=middle bgcolor=#ffffff> 
<table cellspacing=0 width="100%" border=0>
<tbody> 
<tr bgcolor="#F2F2F2"> 
<td align=middle colspan=4 bgcolor="#F2F2F2"> 
<div align="left"><b>Search Results</b></div>
</td>
</tr>
<tr bgcolor="#F2F2F2"> 
<td align=middle colspan=4 bgcolor="#FFFFFF"> 
<div align="left"></div>
<p align="left"> 
<!-- 
The Start of the search specific html code. 
It needs a look and feel update. 
//-->
</p>
<table width="95%" border="0" cellspacing="1" cellpadding="1" align="center">
<tr bgcolor="#330099"> 
<td bgcolor="#FFFFFF"> 
<div align="left"><font color="#FFFFFF"><b> <font color="#666666">You 
searched for</font><font color="#000000"> </font></b><font color="#000000"><font color="#FF0000"><%= strKeyWord%></font></font></font></div>
</td>
</tr>
<%
' Only to the search if we got at least one keyword
if (strKeyWord <> "") then

' Call the sub that gets all the files 
call getCompleteFileList(objFolder, "")

' Take the big ole string the contains all the files seperated by commas and chop it up.
arrFileList = split(strListofFiles,",")

For i=0 to UBound(arrFileList)

' Open the current file and read everything into a single string.
' If the files are huge this could eat a lot or resources.
Set objCheckFile = objFS.OpenTextFile(strSitePath + "\" + arrFileList(i),1,false,0)
strFileContents = objCheckFile.ReadAll

' Default the search flag to false.
bKeyWordFound = false

' For each keyword entered search the file.
for j = 0 to UBound(arrKeyWords) 
returnValue = InStr(1,strFileContents,arrKeyWords(j),1)

' If the returnValue isn't zero the keyword was found
' Set the search flage to true and short cut out of the loop.
if (returnValue <> 0) then
bKeyWordFound = true
j = UBound(arrKeyWords)
end if
next

' If a keyword was found include this file in the list.
if (bKeyWordFound) then

' Keep track of the number of results and grab the title of the page for the search display 
iReturnCount = iReturnCount + 1

dim startChar, endChar
startChar = InStr(1,strFileContents,"<title>",1)
endChar = InStr(1,strFileContents,"</title>",1)

if (startChar = 0 OR endChar = 0 OR ((startChar + 7) > (endChar - 7))) then
%>
<tr> 
<td><font face="Arial, Helvetica, sans-serif" size="2"><a href="<%= arrFileList(i) %>"><%= arrFileList(i) %></a> <%= arrFileList(i) %></font></td>
</tr>
<% 
else 
strPageTitle = mid(strFileContents,InStr(1,strFileContents,"<title>",1) + 7, InStr(1,strFileContents,"</title>",1) - InStr(1,strFileContents,"<title>",1) - 7)

if (strPageTitle = "") then
strPageTitle = arrFileList(i)
end if
%>
<tr> 
<td><font face="Arial, Helvetica, sans-serif" size="2"><a href="<%= arrFileList(i) %>"><%= strPageTitle%>"</a> <%= arrFileList(i) %></font></td>
</tr>
<% 
end if
end if

' Close the file so we can open another one. 
objCheckFile.Close
Next

end if
%>
<tr> 
<td><font face="Arial, Helvetica, sans-serif" size="2" color="#999999"><%= iReturnCount%> pàgina(es) trobada (es)</font></td>
</tr>
<tr> 
<td>&nbsp;</td>
</tr>
<%

' Clean up all the objects used.
set objCheckFile = Nothing
set File = Nothing
set objFiles = Nothing
set objFolder = Nothing
set objFS = Nothing

%>
</table>
<!-- the end of the search html -->
</td>
</tr>
</tbody> 
</table>
</td>
</tr>
</tbody> 
</table>
</td>
</tr>
</tbody> 
</table>
</td>
</tr>
</tbody> 
</table>
<p>&nbsp;</p>
</body>
</html>
Espero que te pueda ayudar. Saludos.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:56.