Don't like ads? PRO users don't see any ads ;-)
Guest

wikibot.py

By: a guest on Apr 29th, 2012  |  syntax: Python  |  size: 3.32 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import re
  2. import urllib2
  3. from urlparse import urlparse
  4. import os
  5.  
  6. link=re.compile(r'''<a.*?href=["'`](.+?)["'`].*?>.*?</a>''',re.IGNORECASE)
  7.  
  8. def get_links(code):
  9.         m=re.findall(link,code)
  10.         return m
  11.         for x in range(len(m)):
  12.                 m[x]=m[x].groups()[1]
  13.         return m
  14.  
  15. def get_html(url):
  16.         try:
  17.                 opener=urllib2.build_opener()
  18.                 opener.addheaders=[('User-agent','Mozilla/5.0')]
  19.                 infile=opener.open(url)
  20.                 return infile.read()
  21.         except urllib2.HTTPError,error:
  22.                 return error.read()
  23.  
  24. #remove media links and add the host to relative links
  25. def fix(links,host,path):
  26.         l=0
  27.         while l<len(links):
  28.                 #check for media
  29.                 parts=os.path.splitext(links[l])
  30.                 if len(parts)>1 and parts[1][1:].lower() in ['png','gif','svg']:
  31.                         del links[l]
  32.                         continue
  33.                 url=urlparse(links[l])
  34.                 #check for external links
  35.                 if url.netloc!='' and url.netloc!=host:
  36.                         del links[l]
  37.                         continue
  38.                 if ':' in url.path:
  39.                         del links[l]
  40.                         continue
  41.                 #probably a link to the same site
  42.                 else:
  43.                         links[l]='http://'+host+url.path
  44.                 l+=1
  45.         return links
  46.  
  47. def valid_links(url):
  48.         u=urlparse(url)
  49.         return list(set(fix(get_links(get_html(url)),u.netloc,u.path)))
  50.  
  51. class tree(list):
  52.         def __init__(self,value=None,children=[]):
  53.                 list.__init__(self,children)
  54.                 self.value=value
  55.                 self.parent=None
  56.        
  57.         #def __str__(self):
  58.         #       return '(%s)'%self.value+list.__str__(self)
  59.        
  60.         def __repr__(self):
  61.                 return 'tree(%r,%s)'%(self.value,list.__repr__(self))
  62.                
  63.         def append(self,node):
  64.                 if type(node)==tree:
  65.                         node.parent=self
  66.                         list.append(self,node)
  67.                 else:
  68.                         node=tree(node)
  69.                         node.parent=self
  70.                         list.append(self,node)
  71.        
  72.         def leaves(self):
  73.                 if len(self)==0:
  74.                         return [self]
  75.                 step=[0]
  76.                 current=self[0]
  77.                 ret=[]
  78.                 while id(current)!=id(self) and len(step)>0 and len(self)>step[-1]:
  79.                         if len(current)==0:
  80.                                 ret.append(current)
  81.                                 current=current.parent
  82.                                 step.pop()
  83.                                 if len(step)>0:
  84.                                         step[-1]+=1
  85.                                 continue
  86.                         if len(current)>step[-1]:
  87.                                 current=current[step[-1]]
  88.                                 step.append(0)
  89.                         else:
  90.                                 while len(current)<=step[-1] and id(current)!=id(self) and len(self)>step[-1]:
  91.                                         current=current.parent
  92.                                         step.pop()
  93.                                         if len(step)>0:
  94.                                                 step[-1]+=1
  95.                 return ret
  96.        
  97.         def unique(self,values):
  98.                 if len(self)==0:
  99.                         return values
  100.                 step=[0]
  101.                 current=self[0]
  102.                 while id(current)!=id(self) and len(step)>0 and len(self)>step[-1]:
  103.                         if current.value in values:
  104.                                 del values[values.index(current.value)]
  105.                         if len(current)>step[-1]:
  106.                                 current=current[step[-1]]
  107.                                 step.append(0)
  108.                         else:
  109.                                 while len(step)>0 and len(current)<=step[-1] and id(current)!=id(self) and len(self)>step[-1]:
  110.                                         current=current.parent
  111.                                         step.pop()
  112.                                         if len(step)>0:
  113.                                                 step[-1]+=1
  114.                 return values
  115.  
  116. def parse_until(start,end):
  117.         links=tree(start)
  118.         while True:
  119.                 leaves=links.leaves()
  120.                 for leaf in leaves:
  121.                         page=valid_links(leaf.value)
  122.                         if end in page:
  123.                                 current=leaf
  124.                                 trace=[end,leaf.value]
  125.                                 while current!=links:
  126.                                         current=current.parent
  127.                                         trace.append(current.value)
  128.                                 trace.reverse()
  129.                                 return trace
  130.                         links.unique(page)
  131.                         for p in page:
  132.                                 leaf.append(p)
  133.  
  134. def format(links):
  135.         s=''
  136.         for l in links:
  137.                 u=urlparse(l)
  138.                 s+=u.path[len('/wiki/'):].replace('_',' ')+' > '
  139.         return s[:-3]
  140.  
  141. print format(parse_until('http://en.wikipedia.org/wiki/Goku','http://en.wikipedia.org/wiki/Dojo'))