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.

122 lines
4.0 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
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
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. try:
  8. import sys
  9. if 'threading' in sys.modules:
  10. del sys.modules['threading']
  11. print('threading module loaded before patching!')
  12. print('threading module deleted from sys.modules!\n')
  13. import gevent
  14. from gevent import monkey, pool
  15. monkey.patch_all()
  16. gevent_installed = True
  17. except:
  18. print("Gevent does not installed. Parsing process will be slower.")
  19. gevent_installed = False
  20. class Crawler:
  21. def __init__(self, url, outputfile='sitemap.xml', logfile='error.log', oformat='xml'):
  22. self.url = url
  23. self.logfile = open(logfile, 'a')
  24. self.oformat = oformat
  25. self.outputfile = outputfile
  26. # create lists for the urls in que and visited urls
  27. self.urls = set([url])
  28. self.visited = set([url])
  29. self.exts = ['htm', 'php']
  30. self.allowed_regex = '\.((?!htm)(?!php)\w+)$'
  31. def set_exts(self, exts):
  32. self.exts = exts
  33. def allow_regex(self, regex=None):
  34. if not regex is None:
  35. self.allowed_regex = regex
  36. else:
  37. allowed_regex = ''
  38. for ext in self.exts:
  39. allowed_regex += '(!{})'.format(ext)
  40. self.allowed_regex = '\.({}\w+)$'.format(allowed_regex)
  41. def crawl(self, echo=False, pool_size=1):
  42. self.echo = echo
  43. self.regex = re.compile(self.allowed_regex)
  44. if gevent_installed and pool_size > 1:
  45. self.pool = pool.Pool(pool_size)
  46. self.pool.spawn(self.parse_gevent)
  47. self.pool.join()
  48. else:
  49. while len(self.urls) > 0:
  50. self.parse()
  51. if self.oformat == 'xml':
  52. self.write_xml()
  53. def parse_gevent(self):
  54. self.parse()
  55. while len(self.urls) > 0 and not self.pool.full():
  56. self.pool.spawn(self.parse_gevent)
  57. def parse(self):
  58. if self.echo:
  59. if not gevent_installed:
  60. print('{} pages parsed :: {} pages in the queue'.format(len(self.visited), len(self.urls)))
  61. else:
  62. print('{} pages parsed :: {} parsing processes :: {} pages in the queue'.format(len(self.visited), len(self.pool), len(self.urls)))
  63. # Set the startingpoint for the spider and initialize
  64. # the a mechanize browser object
  65. if not self.urls:
  66. return
  67. else:
  68. url = self.urls.pop()
  69. br = mechanize.Browser()
  70. try:
  71. response = br.open(url)
  72. if response.code >= 400:
  73. self.errlog("Error {} at url {}".format(response.code, url))
  74. return
  75. for link in br.links():
  76. newurl = urlparse.urljoin(link.base_url, link.url)
  77. #print newurl
  78. if self.is_valid(newurl):
  79. self.visited.update([newurl])
  80. self.urls.update([newurl])
  81. except Exception, e:
  82. self.errlog(e.message)
  83. br.close()
  84. del(br)
  85. def is_valid(self, url):
  86. valid = False
  87. if url in self.visited:
  88. return False
  89. if not self.url in url:
  90. return False
  91. if re.search(self.regex, url):
  92. return False
  93. return True
  94. def errlog(self, msg):
  95. self.logfile.write(msg)
  96. self.logfile.write('\n')
  97. def write_xml(self):
  98. of = open(self.outputfile, 'w')
  99. of.write('<?xml version="1.0" encoding="utf-8"?>\n')
  100. 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')
  101. url_str = '<url><loc>{}</loc></url>\n'
  102. while self.visited:
  103. of.write(url_str.format(self.visited.pop()))
  104. of.write('</urlset>')
  105. of.close()