Buscador de texto en ASP

LoginLogin     BuscarBuscar   RegistrarseRegistrarse  PerfilPerfil   Ver M. privadosMsg. privados   MiembrosMiembros   Grupos de UsuariosGrupos Usuarios   FAQFAQ

Buscador de texto en ASP

Buscador de texto en ASP

 


Agregar esta página a tu escritorioAgr. Escritorio
Agregar a tus favoritosAgr. Favoritos
Enviar esta página a tus amigosEnviar Amigo
Imprimir esta PáginaImprimir


Google

Buscador de texto en ASP
 
Forum    Foros de discusión -> Asp / VBScript
Publicar nuevo temaResponder al tema
Ver tema anterior :: Ver tema siguiente  
Mensaje
Asunto: Buscador de texto en ASP       Mensaje Publicado: Mar Ene 03, 2006 1:33 am Responder citando
 
 
Script para buscar texto en las páginas html. No sirve para extensiones asp que contengan código, pues es una búsqueda en archivos de texto.
Por tanto. Aún en el caso del html, si buscamos la palabra table, nos saldrán todas las páginas html que tengamos y contengan una tabla. Por lo que tiene sus pegas. Igualmente si el sitio es muy grande, la búsqueda puede eternizarse.

Cambiando la extensión, puede buscar en extensiones. TXT, NFO, u otras que contengan texto plano.



Formulario de búsqueda
-------------------------------------------------------


<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">Buscar</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>
<!--
Formulario de búsqueda. A incluir en cada página que se quiera incluir el servicio de buscador en el sitio
//-->
<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="Buscar" name=search>
</td>
</form>
<!--
fin del formulario
//-->
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>






buscar.asp Código fuente:
-------------------------------------------------------
<%@ Language=VBScript %>

<%

Option Explicit
Response.Buffer = True

' Dimensionar variables para contener objetos de Archivos.
dim objFS, objFolder, objFiles, File, FileName, objCheckFile, strSitePath
set objFS = server.CreateObject("Scripting.FileSystemObject")

dim strListofFiles, arrFileList, strPageTitle, iReturnCount
dim objFolders

strListofFiles = ""
iReturnCount = 0

' Dimensionar Valores de busqueda, Espacio de la búsqueda, Y valores de Retorno
dim strKeyWord, strFileContents, returnValue, arrKeyWords
dim bKeyWordFound, i, j

' Obtener el path del directorio actual
strSitePath = Server.MapPath(".")

' Almacenar el texto y dividir por los espacios entre palabras y almacenarlos en un array con las claves de búsqueda
strKeyWord = Trim(request("txtKeyWord"))
arrKeyWords = split(strKeyWord," ")

' Obtner el listado de objetos de archivo del directorio.
Set objFolder = objFS.GetFolder(strSitePath)


'************************************************************************************************************************
' Subrutina que recolecta todos los archivos con extensión .htm y .html y recorre el arbol de directorios recursivamente
'************************************************************************************************************************
sub getCompleteFileList(inFolder, Path)

dim oFiles, oFolders, Folder, sPath

' Recolectar todos los nombres de archivos y subdirectorios
Set oFiles = inFolder.Files
Set oFolders = inFolder.SubFolders

'Si encontramos un subdirectorio, obtenemos la trayectoria parcial
if (Path <> "") then
sPath = Path + "\"
end if


' Añadir cada elemento .htm y .html a una lista
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

' Buscaer en los subdirectorios por archivos html
For Each Folder in oFolders
if (Folder.Name <> "images" AND Folder.Name <> "stats") then
call getCompleteFileList(Folder, sPath + Folder.Name)
end if
Next

' Liberar los objetos de la memoria
set File = Nothing
set oFiles = Nothing
set Folder = Nothing
set oFolders = Nothing

end sub

%>
<--!Codigo html a incluir en el mismo archivo buscar.asp. Constituye la impresión de los resultados -->
<html>
<head>
<title>Resultados de la búsqueda</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">
<!--
Comienzo de la tabla de salida con la búsqeda
//-->
</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>
<%
'Construimos líneas de la tabla con los resultados obtenidos
' Validar que introducimos algún caracter
if (strKeyWord <> "") then

' Llamada a la subrutina que contiene la lista de archivos html de nuestra web.
call getCompleteFileList(objFolder, "")

' Take the big ole string the contains all the files seperated by commas and chop it up.
'Construir un array con la lista de archivos separados por coma
arrFileList = split(strListofFiles,",")

For i=0 to UBound(arrFileList)

'Primero abrimos la cadena completa de archivos del sitio
'Si los archivos son muy grandes, puede consumir muchos recursos.
Set objCheckFile = objFS.OpenTextFile(strSitePath + "\" + arrFileList(i),1,false,0)
strFileContents = objCheckFile.ReadAll

' Por defecto encontrado resultados individuales es falso
bKeyWordFound = false

'Buscamos ahora por cada palabra individual de la búsqueda
'Si solo buscamos literales, nos la podemos ahorrar
for j = 0 to UBound(arrKeyWords)
returnValue = InStr(1,strFileContents,arrKeyWords(j),1)

'Si el resultado no es cero, la palabra ha sido encontrado
'poner la variable de bandera a cierto, y salir del bucle
if (returnValue <> 0) then
bKeyWordFound = true
j = UBound(arrKeyWords)
end if
next

' Si la palabra ha sido encontrada, incluir el archivo en los resultados
if (bKeyWordFound) then

' Cuenta del número de resultados y muestra el título de la página en los resultaos
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

'Cerrar el objeto de modo que podamos abrir otro
objCheckFile.Close
Next

end if
%>
<tr>
<td><font face="Arial, Helvetica, sans-serif" size="2" color="#999999"><%= iReturnCount%> Paginas encontradas</font></td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<%

' limplieza de memoria de los objetos.
set objCheckFile = Nothing
set File = Nothing
set objFiles = Nothing
set objFolder = Nothing
set objFS = Nothing

%>
</table>
<!-- fin del codigo html de los resultados -->
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
</body>
</html>
 
bportal
Site Admin
Registrado: 01 Sep 2004
Mensajes: 29
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email
Mostrar mensajes de anteriores:   
Publicar nuevo temaResponder al tema
   Foros de discusión -> Asp / VBScript Todas las horas son GMT
 
Página 1 de 1
 
Cambiar a:  
Puede publicar nuevos temas   -   No puede responder a temas   -   No puede editar sus mensajes   -   No puede borrar sus mensajes   -   No puede votar en encuestas   -  
 


 
Foros, Índice e Inicio de los forums  
Informe de Abuso, sugerencia o Error en esta página
Navegue hasta la página erronea, y pinche
Quiero ser Moderador
Quiero Sujerir un Foro

Forotopía, no se hace responsable de los comentarios y post de los miembros de este foro. No tiene ningún típo de vinculación con los autores o moderadores, mas que las de su filiación. Estando estos sujetos a las condiciones de utilización de este sitio.

Si usted cree que los contenidos datos u opiniones vulneran o lesionan algún derecho particular propio o de un tercero. Por favor alértenos con un aviso de abuso. Muchas gracias por su interés y colaboración. Enlaces

© Hector Fernández Pereda -- Europe -- Spain -- Asturias   @Email
Administrador