-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhngspider.py
78 lines (64 loc) · 2.51 KB
/
hngspider.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
from urllib import urlopen
from link_finder import LinkFinder
from domain import *
from general import *
class HngSpider:
# Class Variables (Shared among all instances)
project_name = ''
base_url = ''
domain_name = ''
queue_file = ''
crawled_file = ''
queue = set()
crawled = set()
def __init__(self, project_name, base_url, domain_name):
HngSpider.project_name = project_name
HngSpider.domain_name = domain_name
HngSpider.base_url = base_url
HngSpider.queue_file = HngSpider.project_name + '/queue.txt'
HngSpider.crawled_file = HngSpider.project_name + '/crawled.txt'
self.boot()
self.crawl_page('First spider', HngSpider.base_url)
@staticmethod # Since boot is a static method
def boot():
create_project_dir(HngSpider.project_name)
create_data_files(HngSpider.project_name, HngSpider.base_url)
HngSpider.queue = file_to_set(HngSpider.queue_file)
HngSpider.crawled = file_to_set(HngSpider.crawled_file)
@staticmethod # Since crawl_page is also a static method
def crawl_page(thread_name, page_url):
if page_url not in HngSpider.crawled:
print(thread_name + ' now crawling ' + page_url)
print('Queue ' + str(len(HngSpider.queue)) + '| crawled' + str(len(HngSpider.crawled)))
HngSpider.add_links_to_queue(HngSpider.gather_links(page_url))
HngSpider.queue.remove(page_url)
HngSpider.crawled.add(page_url)
HngSpider.update_files()
@staticmethod
def gather_links(page_url):
html_string = ''
try:
response = urlopen(page_url)
if response.getheader('Content-Type') == 'text/html':
html_bytes = response.read()
html_string = html_bytes.decode("utf-8")
finder = LinkFinder(HngSpider.base_url, page_url)
finder.feed(html_string)
except:
print ('Error: Unable to crawl page')
return set()
return finder.page_links()
@staticmethod
def add_links_to_queue(links):
for url in links:
if url in HngSpider.queue:
continue
if url in HngSpider.crawled:
continue
if HngSpider.domain_name not in url:
continue
HngSpider.queue.add(url)
@staticmethod
def update_files():
set_to_file(HngSpider.queue, HngSpider.queue_file)
set_to_file(HngSpider.crawled, HngSpider.crawled_file)