-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebCrawler.py
62 lines (48 loc) · 1.31 KB
/
WebCrawler.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
import sys
import requests
from bs4 import BeautifulSoup
TO_CRAWL = []
CRAWLED = set()
def request(url):
header = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"}
try:
response = requests.get(url, headers=header)
return response.text
except KeyboardInterrupt:
sys.exit(0)
except:
pass
def get_links(html):
links = []
try:
soup = BeautifulSoup(html, "html.parser")
tags_a = soup.find_all("a", href=True)
for tag in tags_a:
link = tag["href"]
if link.startswith("http"):
links.append(link)
return links
except:
pass
def crawl():
while 1:
if TO_CRAWL:
url = TO_CRAWL.pop()
html = request(url)
if html:
links = get_links(html)
if links:
for link in links:
if link not in CRAWLED and link not in TO_CRAWL:
TO_CRAWL.append(link)
print("Crawling {}".format(url))
CRAWLED.add(url)
else:
CRAWLED.add(url)
else:
print("Done")
break
if __name__ == "__main__":
url = sys.argv[1]
TO_CRAWL.append(url)
crawl()