-
Notifications
You must be signed in to change notification settings - Fork 0
/
sitemap.py
executable file
·81 lines (57 loc) · 2.81 KB
/
sitemap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#FROM: https://github.com/varelaz/varela-python-sitemap-parser/
import urllib2
import zlib
import lxml.etree
import logging
import traceback
class SiteMaps(object):
def __init__(self, domain, set, recursive):
self.domain = domain
self.sitemaps = []
self.urls = []
self.fetched_sitemaps = []
self.set = set
self.recursive = recursive
def read_robots(self):
try:
robots_link = self.set.get_or_create_link_object(self.set.robots_url, None)
robots_link.is_robots = True
self.set.load_link(robots_link, False, 200)
if robots_link.content:
for line in robots_link.content.split('\n'):
line = line.strip()
if line.lower().startswith('sitemap:'):
self.sitemaps.append(line[len('Sitemap:'):].strip())
except Exception, e:
print "Error Reading Robots: %s"%(traceback.format_exc())
logging.exception(e)
def run(self):
self.read_robots()
self.sitemaps = self.sitemaps or [self.set.default_sitemap_url]
while self.sitemaps and len(self.sitemaps) > 0:
sitemap_url = self.sitemaps.pop()
sitemap_link = self.set.get_or_create_link_object(sitemap_url, None)
sitemap_link.is_sitemap = True
self.set.load_link(sitemap_link, False, 200, True)
self.process_sitemap(sitemap_link)
def process_sitemap(self, sitemap_link):
namespaces = [
('sm', 'http://www.sitemaps.org/schemas/sitemap/0.9'),
]
if not sitemap_link.content:
return
xml = sitemap_link.content.encode('utf-8')
parser = lxml.etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8')
tree = lxml.etree.fromstring(xml, parser=parser)
for sitemap in tree.xpath('//sm:sitemap | //sitemap', namespaces=namespaces):
for loc in sitemap.xpath('sm:loc | loc', namespaces=namespaces):
child_sitemap_url = loc.text.strip()
child_sitemap_link = self.set.get_or_create_link_object(child_sitemap_url, sitemap_link)
self.sitemaps.append(child_sitemap_url)
for sitemap in tree.xpath('//sm:url | //url', namespaces=namespaces):
# TODO: add last update date, rank and update frequency
for loc in sitemap.xpath('sm:loc | loc', namespaces=namespaces):
url = loc.text.strip()
self.urls.append(url)
# print 'Found url (%s)'%(url)
link = self.set.get_or_create_link_object(url, sitemap_link)