-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.py
142 lines (135 loc) · 6.43 KB
/
scraper.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Scans for assignments on viggo using requests and the POST method."""
import re
import requests
from requests import Session
import json
def get_links(info):
"""Gets all assignment links from viggo's assignment page."""
with Session() as s: # pylint: disable=invalid-name
login_data = {"UserName": info["username"], "Password": info["password"]}
subdomain, date = info["subdomain"], info["date"]
try:
s.post(f"https://{subdomain}.viggo.dk/Basic/Account/Login", login_data)
except requests.exceptions.SSLError:
try:
s.get("https://viggo.dk")
except requests.exceptions.SSLError:
return "Viggo is currently down."
return "Invalid subdomain"
home_page = s.get(f"https://{subdomain}.viggo.dk/Basic/HomeworkAndAssignment/?date={date}")
home_page = str(home_page.content).replace('\\n', '\n').replace('\\r', '\r').replace('\\xc3\\xb8', 'ø').replace('\\xc3\\xa5', 'å').replace('ø', 'ø').replace('å', 'å').replace('\\xc3\\xa6', 'æ').replace('\\xc3\\x98', 'Ø')
if "page-login" in home_page:
return "Invalid credentials"
return re.findall(
"(?<=<a href=\"/Basic/HomeworkAndAssignment/Details/).*?(?=/#modal)",
home_page,
)
def extract_data(link, home_page, assignment_data):
"""Extracts data from viggo using regex."""
assignment_data["url"].append("https://nr-aadal.viggo.dk/Basic/HomeworkAndAssignment/Details/" + link + "/#modal")
home_page = str(home_page.content)
replacements = {
'\\n': '\n',
'\\r': '\r',
'\\xc3\\xb8': 'ø',
'\\xc3\\xa5': 'å',
'ø': 'ø',
'å': 'å',
'\\xc3\\xa6': 'æ',
'\\xc3\\x98': 'Ø',
' ': '',
'<em>': '',
'</em>': '',
'<ol>': '',
'</ol>': '',
'<li>': '• ',
'</li>': '\r'
}
for string, replacement in replacements.items():
home_page = home_page.replace(string, replacement)
new_subject = re.findall("(?<=class=\"ajaxModal\">).*?(?=</a>)", home_page)
assignment_data["subject"].append(new_subject[0].replace('æ', 'æ'))
new_time = re.findall("(?<=<dd>).*?(?= <)", home_page)
assignment_data["time"].append(new_time[0])
new_description = re.findall("(?<=<div class=\"content\">).*?(?=</div>)", home_page)
#assignment_data["description"].append(new_description[0])
new_author = re.findall("(?<=<p><small class=\"muted\">).*?(?=</small></p>)", home_page)
assignment_data["author"].append(new_author[0])
new_file = re.findall("(?<=<a class=\"ajaxModal\" href=\").*?(?=\")", home_page)
if new_file:
for j in enumerate(new_file):
j = j[0]
new_file[j] = "https://nr-aadal.viggo.dk" + new_file[j]
file_collection = str(new_file).replace('[', '').replace(']', '').replace('\'', '')
else:
file_collection = "None"
assignment_data["files"].append(file_collection)
new_file_name = re.findall("(?<=<span>).*?(?=</span>)", home_page)
if new_file_name:
for j in enumerate(new_file_name):
j = j[0]
new_file_name[j] = new_file_name[j].replace('æ', 'æ')
file_name_collection = str(new_file_name).replace('[', '').replace(']', '').replace('\'', '')
else:
file_name_collection = "None"
assignment_data["file_names"].append(file_name_collection)
return assignment_data, new_description[0]
def get_links_in_post(description):
"""Gets non-labelled hyperlinks in a post and doubles them for future formatting."""
link_in_post = ''
if "\" rel=\"noopener noreferrer\" target=\"_blank\">" in description:
link_in_post = re.findall("(?<=\" rel=\"noopener noreferrer\" target=\"_blank\">).*?(?=</a>)", description)[0]
return link_in_post, link_in_post + link_in_post
def remove_hex(description, double_link, link_in_post):
"""Filters out hexadecimal symbols from data."""
pre_hex_removal = description.replace('<p>', '\n').replace('</p>', '').replace('<strong>', '').replace('</strong>', '').replace('<br>', '').replace('<a href=\"', '').replace('\" rel=\"noopener noreferrer\" target=\"_blank\">', '').replace('</a>', '').replace(double_link, link_in_post).replace('&', '&')
pre_hex_removal = pre_hex_removal.replace('\\x', '|')
hex_to_remove = re.findall("(?<=\\|).*?(?= |\n)", pre_hex_removal)
for j in enumerate(hex_to_remove):
j = j[0]
replacements = hex_to_remove[j]
pre_hex_removal = pre_hex_removal.replace(replacements, '')
description = pre_hex_removal.replace('|', '')
return description
def format_links(link_in_post, description):
"""Formats links to labelled hyperlinks if possible."""
if link_in_post != '':
target = re.findall("(?<=rel=\"noopener noreferrer\" target=\"_blank\">).*?(?=</a>)", description)
href = re.findall("(?<=<a href=\").*?(?=\")", description)
for j in enumerate(href):
j = j[0]
if target[j] != href[j]:
description = description.replace(target[j], '').replace(href[j], f"[{target[j]}]({href[j]})")
return description
def scrape_page(link, info):
"""Scrapes the contents of a viggo assignment page."""
with Session() as s: # pylint: disable=invalid-name
login_data = {"UserName": info["username"], "Password": info["password"]}
subdomain = info["subdomain"]
s.post(f"https://{subdomain}.viggo.dk/Basic/Account/Login", login_data)
home_page = s.get(f"https://{subdomain}.viggo.dk/Basic/HomeworkAndAssignment/Details/{link}/#modal")
return home_page
def get_assignments(info):
"""Function that scans assignments then returns each element in a dictionary."""
assignment_data = {
"subject": [],
"time": [],
"description": [],
"author": [],
"files": [],
"file_names": [],
"url": [],
"errors": None
}
links = get_links(info)
if type(links) is not list:
return {"errors": [links]}
for i in enumerate(links):
i = i[0]
home_page = scrape_page(links[i], info)
assignment_data, description = extract_data(links[i], home_page, assignment_data)
link_in_post, double_link = get_links_in_post(description)
description = remove_hex(description, double_link, link_in_post)
description = format_links(link_in_post, description)
assignment_data['description'].append(description)
return assignment_data