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.

82 lines
2.6 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
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 = set([url])
  18. self.visited = set([url])
  19. self.exts = ['htm', 'php']
  20. self.allowed_regex = '(\w+)\.((?!htm)(?!rar)\w+)$'
  21. def set_exts(self, exts):
  22. self.exts = exts
  23. def allow_regex(self, regex=None):
  24. if not regex is None:
  25. self.allowed_regex = regex
  26. else:
  27. allowed_regex = ''
  28. for ext in self.exts:
  29. allowed_regex += '(!{})'.format(ext)
  30. self.allowed_regex = '(\w+)\.({}\w+)$'.format(allowed_regex)
  31. def crawl(self):
  32. self.regex = re.compile(self.allowed_regex)
  33. while len(self.urls)>0:
  34. try:
  35. url = self.urls.pop()
  36. self.br.open(url)
  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.update([newurl])
  42. self.urls.update([newurl])
  43. except Exception, e:
  44. self.errlog(e.message)
  45. if self.oformat == 'xml':
  46. self.write_xml()
  47. def is_valid(self, url):
  48. valid = False
  49. if url in self.visited:
  50. return False
  51. if not self.url in url:
  52. return False
  53. if re.search(self.regex, url):
  54. return False
  55. return True
  56. def errlog(self, msg):
  57. self.logfile.write(msg)
  58. self.logfile.write('\n')
  59. def write_xml(self):
  60. of = open(self.outputfile, 'w')
  61. of.write('<?xml version="1.0" encoding="utf-8"?><!--Generated by Screaming Frog SEO Spider 2,55-->\n')
  62. 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')
  63. url_str = '<url><loc>{}</loc></url>\n'
  64. while self.visited:
  65. of.write(url_str.format(self.visited.pop()))
  66. of.write('</urlset>')
  67. of.close()