Sitemap generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.6 KiB

9 years ago
  1. import urllib
  2. from bs4 import BeautifulSoup
  3. import urlparse
  4. import mechanize
  5. import pickle
  6. import re
  7. class Crawler:
  8. def __init__(self, url, outputfile='sitemap.xml', logfile='error.log', oformat='xml'):
  9. # Set the startingpoint for the spider and initialize
  10. # the a mechanize browser object
  11. self.url = url
  12. self.br = mechanize.Browser()
  13. self.logfile = open(logfile, 'a')
  14. self.oformat = oformat
  15. self.outputfile = outputfile
  16. # create lists for the urls in que and visited urls
  17. self.urls = [url]
  18. self.visited = [url]
  19. self.excepted = []
  20. self.exts = ['htm', 'php']
  21. self.allowed_regex = '(\w+)\.((?!htm)(?!rar)\w+)$'
  22. def set_exts(self, exts):
  23. self.exts = exts
  24. def allow_regex(self, regex=None):
  25. if not regex is None:
  26. self.allowed_regex = regex
  27. else:
  28. allowed_regex = ''
  29. for ext in self.exts:
  30. allowed_regex += '(!{})'.format(ext)
  31. self.allowed_regex = '(\w+)\.({}\w+)$'.format(allowed_regex)
  32. def crawl(self):
  33. self.regex = re.compile(self.allowed_regex)
  34. while len(self.urls)>0:
  35. try:
  36. self.br.open(self.urls[0])
  37. for link in self.br.links():
  38. newurl = urlparse.urljoin(link.base_url,link.url)
  39. #print newurl
  40. if self.is_valid(newurl):
  41. self.visited.append(newurl)
  42. self.urls.append(newurl)
  43. except Exception, e:
  44. self.errlog(e.message)
  45. self.urls.pop(0)
  46. if self.oformat == 'xml':
  47. self.write_xml()
  48. def is_valid(self, url):
  49. valid = False
  50. if url in self.visited and not url in self.excepted:
  51. return False
  52. if not self.url in url:
  53. return False
  54. if re.search(self.regex, url):
  55. return False
  56. return True
  57. def errlog(self, msg):
  58. self.logfile.write(msg)
  59. self.logfile.write('\n')
  60. def write_xml(self):
  61. of = open(self.outputfile, 'w')
  62. of.write('<?xml version="1.0" encoding="utf-8"?><!--Generated by Screaming Frog SEO Spider 2,55-->\n')
  63. of.write('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">\n')
  64. url_str = '<url><loc>{}</loc></url>\n'
  65. for url in self.visited:
  66. of.write(url_str.format(url))
  67. of.write('</urlset>')
  68. of.close()