-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcrawler.py
More file actions
56 lines (44 loc) · 1.35 KB
/
crawler.py
File metadata and controls
56 lines (44 loc) · 1.35 KB
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
from bs4 import BeautifulSoup
from urllib import urlopen
START_URL = '/wiki/Cat'
URL_BASE = 'https://en.wikipedia.org'
MAX_LINKS = 1000
DOC_DIRECTORY = 'test_docs/'
def run():
visited = set()
links = {START_URL}
while len(visited) < MAX_LINKS:
v, l = crawl(links, visited)
visited |= v
links |= l
def crawl(links, visited):
new_links = set()
for link in links:
cur_link = URL_BASE + link
if len(visited) > MAX_LINKS:
break;
if link not in visited:
try:
text = download(cur_link)
visited.add(link)
filename = '%stest%d.html' % (DOC_DIRECTORY, len(visited))
write_to_file(text, filename)
new_links |= (find_links(BeautifulSoup(text, 'lxml')))
except IOError:
print('%s failed to download.' % link)
continue
return (visited, new_links)
def download(link):
return urlopen(link).read()
def write_to_file(text, filename):
with open(filename, 'w') as outfile:
outfile.write(text)
def find_links(soup):
return set(filter(proper_url, [a.get('href') for a in soup.find_all('a')]))
def proper_url(url):
if url is None:
return False
else:
return '//' not in url
if __name__ == '__main__':
run()