Foros del Web » Programando para Internet » Python »

Problema

Estas en el tema de Problema en el foro de Python en Foros del Web. EL PROBLEMA QUE TENGO, ES QUE CUANDO QUIERO ACCEDER A LA SIGUIENTE PAGINA: http://vimeo.com/ajax/user/home_videos?&jdata={"page":'+str(k)+'}' me tira una serie de errores, que con otra pagina no ...
  #1 (permalink)  
Antiguo 02/11/2010, 12:59
 
Fecha de Ingreso: noviembre-2010
Mensajes: 33
Antigüedad: 13 años, 5 meses
Puntos: 1
Exclamación Problema

EL PROBLEMA QUE TENGO, ES QUE CUANDO QUIERO ACCEDER A LA SIGUIENTE PAGINA:
http://vimeo.com/ajax/user/home_videos?&jdata={"page":'+str(k)+'}'

me tira una serie de errores, que con otra pagina no me deja, la idea del programa es hacer un crawler, y que los resultados los escriba en un xml.

directamente no me deja bajar el html de la pagina.

los errores que me tira los dejo debajo del porgrama.




import re
import urllib.request
import datetime


class Links():
def __init__(self,url):
self.__direccion=url
def setter(self,url):
self.__direccion=url

def adhtml(self):
f= urllib.request.urlopen(self.__direccion)
a=f.read()
return a


def buscaVideo(self, html):
try:

Exprecion = re.compile('<a\s*href=[\'|"](.*?)[\'|"]')
finalVideo=[]


ec = Exprecion.findall(str(html))



for i in range(0,len(ec)):
if (re.match("[0-9]*",ec[i])):
finalVideo.append(ec[i])

except:
print("ocurrio un error")



return (finalVideo)


def buscaDescripcion(self, html):

Exprecion = re.compile('<div id="description">(.*?)<br><br>(.*?)<br><br>(.*?)<b r><br>(.*?)<br><br>(.*?)<br><br>(.*?) </div>')



ec = Exprecion.findall(str(html))



return (ec)


def buscaRate(self,html):

Exprecion = re.compile('<td>(.*?)</td>')



ec = Exprecion.findall(str(html))



return (ec)

def buscaTitulo(self,html):

Exprecion = re.compile('<div class="title">(.*?)</div>')




ec = Exprecion.findall(str(html))



return (ec)
def buscaCategoria(self,html):

Exprecion = re.compile('<p id="eow-category"><a href="/.*">(.*?)</a></p>')




ec = Exprecion.findall(str(html))



return (ec)



if __name__ == '__main__':
url='vimeo.com/ajax/user/home_videos?&jdata={"page":1}'
link=Links(url)
fecha=datetime.date.today()
dia=(str(fecha))
print(fecha)


loco=open("videosVimeo.txt","w")




loco.write("<?xml>\n")
loco.write('<list origin="vimeo" date="'+ dia +'">\n')
for k in range(1,35):
url='http://vimeo.com/ajax/user/home_videos?&jdata={"page":'+k+'}'




print(url)
print (url.__repr__())





link.setter(url)
html=link.adhtml()


arrayVideo=link.buscaVideo(html)

s=set(arrayVideo)
for h in s:

link.setter("http://www.vimeo.com"+h)
html=link.adhtml()
a=link.buscaDescripcion(html)
rate=link.buscaRate(html)
titulo=link.buscaTitulo(html)






loco.write('\t<item>\n')
loco.write('\t\t <title>'+ titulo[0] + '</title>\n')
loco.write('\t\t<refer>http://www.vimeo.com"'+h+'"</refer>\n')
loco.write('\t\t<rate>'+ rate[1] +'</rate>\n')
loco.write('\t\t<description>' +a[2]+ '</description>\n')
#loco.write('\t\t<category>'+categoria[0]+'</category>\n')
loco.write('\t</item>\n')






loco.close()







print("Aca salen los videos")
for j in range(1,len(arrayVideo)):
print(arrayVideo[j])






--------------------------------------------------------------------------------------------------------Traceback (most recent call last):
File "C:\Users\carta\Desktop\kavesa\PeN DRIVE\paquete\Spider vimeo\linksvimeo.py", line 122, in <module>
html=link.adhtml()
File "C:\Users\carta\Desktop\kavesa\PeN DRIVE\paquete\Spider vimeo\linksvimeo.py", line 13, in adhtml
f= urllib.request.urlopen(self.__direccion)
File "C:\Python31\lib\urllib\request.py", line 121, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python31\lib\urllib\request.py", line 355, in open
response = meth(req, response)
File "C:\Python31\lib\urllib\request.py", line 467, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python31\lib\urllib\request.py", line 393, in error
return self._call_chain(*args)
File "C:\Python31\lib\urllib\request.py", line 327, in _call_chain
result = func(*args)
File "C:\Python31\lib\urllib\request.py", line 475, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
  #2 (permalink)  
Antiguo 02/11/2010, 13:39
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Problema

No uses expresiones regulares para parsear html o xml en vez de eso usa un parser.
Como lxml o BeautifulSoup

Al parecer no es tan fácil de hacer un spider. Lo probe con python 2.6 y me marco esto.
Código HTML:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3.     <title>Vimeo / 403 Forbidden</title>
  4.        
  5.     <style type="text/css">
  6.         body {
  7.             background:red;
  8.             font-family:arial,san-serif;
  9.             font-size:18px;
  10.             font-weight:normal;
  11.             color:white;
  12.             margin:75px;
  13.         }
  14.     </style>
  15. </head>
  16.     <p><h1>You are blocked from Vimeo</h1></p>
  17.     <p>The connection you are using has been blocked from communicating with Vimeo's servers. This ban will never be lifted.</p>
  18.     <div style="display:none">1288726562</div>
  19.     <p>If you are human and think this is an error, please <a href="mailto:[email protected]?body=I have been banned. My IP is x.x.x.x and my browser is Python-urllib/1.17">click here</a>.</p>
  20.     <br />
  21.     <p><em>"It's too bad she won't live. But then again, who does?"</em></p>
  22. </body>
  23. </html>

Al parecer también tienes que añadir algunos headers al request que estas haciendo.
  #3 (permalink)  
Antiguo 02/11/2010, 13:42
 
Fecha de Ingreso: noviembre-2010
Mensajes: 33
Antigüedad: 13 años, 5 meses
Puntos: 1
Respuesta: Problema

es python 3... no se si tiene que ver eso me falto aclararlo
  #4 (permalink)  
Antiguo 02/11/2010, 14:46
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Problema

Código Python:
Ver original
  1. #Codigo en python 2.6
  2. import re
  3. import urllib
  4. import datetime
  5.  
  6. class AppURLopener(urllib.FancyURLopener):
  7.     version = "App/1.7"
  8.  
  9. urllib._urlopener = AppURLopener()
  10.  
  11. class Links():
  12.     def __init__(self,url):
  13.         self.__direccion=url
  14.  
  15.     def setter(self,url):
  16.         self.__direccion=url
  17.  
  18.     def adhtml(self):
  19.         try:
  20.             f= urllib.urlopen(self.__direccion)
  21.         except:
  22.             print("Fallo en", self.__direccion)
  23.             raise SystemExit
  24.         a=f.read()
  25.         f.close()
  26.         return a
  27.  
  28.  
  29.     def buscaVideo(self, html):
  30.         try:
  31.             Exprecion = re.compile('<a\s*href=[\'|"](.*?)[\'|"]')
  32.             finalVideo=[]
  33.             ec = Exprecion.findall(str(html))
  34.             for i in range(0,len(ec)):
  35.                 if (re.match("[0-9]*",ec[i])):
  36.                     finalVideo.append(ec[i])
  37.  
  38.         except:
  39.             print("ocurrio un error")
  40.         return (finalVideo)
  41.  
  42.  
  43.     def buscaDescripcion(self, html):
  44.         Exprecion = re.compile('<div id="description">(.*?)<br><br>(.*?)<br><br>(.*?)<b r><br>(.*?)<br><br>(.*?)<br><br>(.*?) </div>')
  45.         ec = Exprecion.findall(str(html))
  46.         return (ec)
  47.  
  48.     def buscaRate(self,html):
  49.         Exprecion = re.compile('<td>(.*?)</td>')
  50.         ec = Exprecion.findall(str(html))
  51.         return (ec)
  52.  
  53.     def buscaTitulo(self,html):
  54.         Exprecion = re.compile('<div class="title">(.*?)</div>')
  55.         ec = Exprecion.findall(str(html))
  56.         return (ec)
  57.    
  58.     def buscaCategoria(self,html):
  59.         Exprecion = re.compile('<p id="eow-category"><a href="/.*">(.*?)</a></p>')
  60.         ec = Exprecion.findall(str(html))
  61.         return (ec)
  62.  
  63. url='vimeo.com/ajax/user/home_videos?&jdata={"page":1}'
  64. link=Links(url)
  65. fecha=datetime.date.today()
  66. dia=(str(fecha))
  67. print(fecha)
  68. loco=open("videosVimeo.txt","w")
  69.  
  70.  
  71. loco.write("<?xml>\n")
  72. loco.write('<list origin="vimeo" date="'+ dia +'">\n')
  73. for k in range(1,35):
  74.     url='http://vimeo.com/ajax/user/home_videos?&jdata={"page":'+str(k)+'}'
  75.     print(url)
  76.     print (url.__repr__())
  77.     link.setter(url)
  78.     html=link.adhtml()
  79.     print html
  80.     arrayVideo=link.buscaVideo(html)
  81.     s=set(arrayVideo)
  82.     for h in s:
  83.         link.setter("http://www.vimeo.com"+h)
  84.         html=link.adhtml()
  85.         a=link.buscaDescripcion(html)
  86.         rate=link.buscaRate(html)
  87.         titulo=link.buscaTitulo(html)
  88.         loco.write('\t<item>\n')
  89.         loco.write('\t\t <title>'+ titulo[0] + '</title>\n')
  90.         loco.write('\t\t<refer>http://www.vimeo.com"'+h+'"</refer>\n')
  91.         loco.write('\t\t<rate>'+ rate[1] +'</rate>\n')
  92.         loco.write('\t\t<description>' +a[2]+ '</description>\n')
  93.         #loco.write('\t\t<category>'+categoria[0]+'</category>\n')
  94.         loco.write('\t</item>\n')
  95.  
  96. loco.close()
  97.  
  98. print("Aca salen los videos")
  99. for j in range(1,len(arrayVideo)):
  100.     print(arrayVideo[j])
Al parecer urllib de python 3.1 no hace muchas cosas por defecto que el de python 2.6 Si
Por cierto tienes problemas con los indices de tus listas. Por eso entre otras cosas es mejor usar un parser.

Codigo en python 3.1
Código Python:
Ver original
  1. import re
  2. import urllib.request
  3. import datetime
  4.  
  5. class Links():
  6.     def __init__(self,url):
  7.         self.__direccion=url
  8.  
  9.     def setter(self,url):
  10.         self.__direccion=url
  11.  
  12.     def adhtml(self):
  13.         user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
  14.         values = {}
  15.         headers = {'User-Agent':user_agent}
  16.         data = urllib.parse.urlencode(values)
  17.         req = urllib.request.Request(url, data, headers)
  18.         f= urllib.request.urlopen(req)
  19.         a=f.read()
  20.         f.close()
  21.         return a
  22.  
  23.  
  24.     def buscaVideo(self, html):
  25.         try:
  26.             Exprecion = re.compile('<a\s*href=[\'|"](.*?)[\'|"]')
  27.             finalVideo=[]
  28.             ec = Exprecion.findall(str(html))
  29.             for i in range(0,len(ec)):
  30.                 if (re.match("[0-9]*",ec[i])):
  31.                     finalVideo.append(ec[i])
  32.  
  33.         except:
  34.             print("ocurrio un error")
  35.         return (finalVideo)
  36.  
  37.  
  38.     def buscaDescripcion(self, html):
  39.         Exprecion = re.compile('<div id="description">(.*?)<br><br>(.*?)<br><br>(.*?)<b r><br>(.*?)<br><br>(.*?)<br><br>(.*?) </div>')
  40.         ec = Exprecion.findall(str(html))
  41.         return (ec)
  42.  
  43.     def buscaRate(self,html):
  44.         Exprecion = re.compile('<td>(.*?)</td>')
  45.         ec = Exprecion.findall(str(html))
  46.         return (ec)
  47.  
  48.     def buscaTitulo(self,html):
  49.         Exprecion = re.compile('<div class="title">(.*?)</div>')
  50.         ec = Exprecion.findall(str(html))
  51.         return (ec)
  52.    
  53.     def buscaCategoria(self,html):
  54.         Exprecion = re.compile('<p id="eow-category"><a href="/.*">(.*?)</a></p>')
  55.         ec = Exprecion.findall(str(html))
  56.         return (ec)
  57.  
  58. url='vimeo.com/ajax/user/home_videos?&jdata={"page":1}'
  59. link=Links(url)
  60. fecha=datetime.date.today()
  61. dia=(str(fecha))
  62. print(fecha)
  63. loco=open("videosVimeo.txt","w")
  64.  
  65.  
  66. loco.write("<?xml>\n")
  67. loco.write('<list origin="vimeo" date="'+ dia +'">\n')
  68. for k in range(1,35):
  69.     url='http://vimeo.com/ajax/user/home_videos?&jdata={"page":'+str(k)+'}'
  70.     print(url)
  71.     print (url.__repr__())
  72.     link.setter(url)
  73.     html=link.adhtml()
  74.     arrayVideo=link.buscaVideo(html)
  75.     s=set(arrayVideo)
  76.     for h in s:
  77.         link.setter("http://www.vimeo.com"+h)
  78.         html=link.adhtml()
  79.         a=link.buscaDescripcion(html)
  80.         rate=link.buscaRate(html)
  81.         titulo=link.buscaTitulo(html)
  82.         loco.write('\t<item>\n')
  83.         if titulo:
  84.             loco.write('\t\t <title>'+ titulo[0] + '</title>\n')
  85.         loco.write('\t\t<refer>http://www.vimeo.com"'+h+'"</refer>\n')
  86.         if len(titulo) > 2:
  87.             loco.write('\t\t<rate>'+ rate[1] +'</rate>\n')
  88.         if len(titulo) > 3:
  89.             loco.write('\t\t<description>' +a[2]+ '</description>\n')
  90.         #loco.write('\t\t<category>'+categoria[0]+'</category>\n')
  91.         loco.write('\t</item>\n')
  92.  
  93. loco.close()
  94.  
  95. print("Aca salen los videos")
  96. for j in range(1,len(arrayVideo)):
  97.     print(arrayVideo[j])
No se si esta bien la identación
  #5 (permalink)  
Antiguo 02/11/2010, 15:31
 
Fecha de Ingreso: noviembre-2010
Mensajes: 33
Antigüedad: 13 años, 5 meses
Puntos: 1
Respuesta: Problema

muchas gracias, ahora por lo menos entra y baja el html

soy nuevo en esto... y no tengo ni idea que hiciste aca:

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {}
headers = {'User-Agent':user_agent}
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
  #6 (permalink)  
Antiguo 02/11/2010, 15:33
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Problema

Bueno solo le añadi el header de User-Agent para que pudiera entrar.
  #7 (permalink)  
Antiguo 02/11/2010, 18:40
 
Fecha de Ingreso: noviembre-2010
Mensajes: 33
Antigüedad: 13 años, 5 meses
Puntos: 1
Respuesta: Problema

realmente te agradezco muchÍsimo tu ayuda!!!!.

gracias gracias gracias y mil gracias mas

Etiquetas: Ninguno
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 12:28.