Guest User

Crawler.py

a guest
Dec 18th, 2015
1,225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. #simple web crawling program
  2. import urllib
  3. import urllib.request
  4. from urllib.parse import urljoin
  5. from bs4 import BeautifulSoup
  6. import sys
  7. import json
  8. import msvcrt
  9.  
  10.  
  11. def startList(links):
  12.     for i in links:
  13.         crawl(i)
  14.         if msvcrt.kbhit():
  15.             if ord(msvcrt.getch()) == 27:
  16.                 break
  17.  
  18.  
  19. def crawl(url):
  20.     print("Opening url " + url + "\n")
  21.     html = urllib.request.urlopen(url)
  22.     print("Parsing HTML \n")
  23.     cleanHtml = BeautifulSoup(html, "html.parser")
  24.     links = {}
  25.     invalidLinks = {}
  26.     try:
  27.         with open('list.txt','r') as f:
  28.             links = json.load(f)
  29.         with open('invalidList.txt','r') as f:
  30.             invalidLinks = json.load(f)
  31.     except ValueError:
  32.         pass
  33.     print("Starting Crawler \n")
  34.     count = 0
  35.     for link in cleanHtml.find_all('a'):
  36.         a = link.get('href')
  37.         if a not in links and a not in invalidLinks and a != '':
  38.             try:
  39.                 print("Link: " + a + "\n")
  40.                 if url not in a:
  41.                     a = urljoin(url,a)
  42.                 if 'http://' != a[:7]:
  43.                     a = 'http://' + a
  44.                 print("New Link: " + a + "\n")
  45.                 try:
  46.                     print("Adding to list\n")
  47.                     newHtml = urllib.request.urlopen(a)
  48.  
  49.                     links[a] = str(newHtml.read())
  50.                     with open('list.txt','w') as f:
  51.                         json.dump(links,f)
  52.                     count += 1
  53.                 except:
  54.                     invalidLinks[a] = 'NULL'
  55.                     with open('invalidList.txt','w') as f:
  56.                         json.dump(invalidLinks,f)
  57.                     print("Invalid url.. ")
  58.                 print("===================")
  59.             except TypeError:
  60.                 pass
  61.         if msvcrt.kbhit():
  62.             if ord(msvcrt.getch()) == 27:
  63.                 break
  64.         else:
  65.             pass
  66.     with open('list.txt','r') as f:
  67.         links = json.load(f)
  68.     print("Starting main loop...")
  69.     startList(links)
  70.  
  71. def main():
  72.     crawl(sys.argv[1])
  73.  
  74.  
  75. if __name__ == '__main__':
  76.     main()
Advertisement
Add Comment
Please, Sign In to add comment