-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathURL_extraction.py
163 lines (107 loc) · 3.86 KB
/
URL_extraction.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# import numpy as np
import os
import pandas as pd
# import json
import re
# import networkx as nx
# import nltk
# import spacy
import urllib.request
from bs4 import BeautifulSoup
from socket import timeout
# Find the json data files from all available folders:
# In[ ]:
data = []
for root, dirs, files in os.walk(os.getcwd()):
for name in files:
if name.endswith((".json")):
data.append(os.path.join(root, name))
# Load json files and make a dataframe for text messages:
# In[ ]:
all_data = []
for i in range(len(data)):
with open(data[i]) as json_file:
df = pd.read_json(json_file)
if 'text' in df.columns:
json_data = pd.DataFrame(df['text'])
all_data.append(json_data)
all_data = pd.concat(all_data)
# Make a dataframe from rows that contain a link (contain 'http'):
# In[ ]:
URL_df = all_data[all_data['text'].str.contains('http')]
# Function which finds URLs for each row in the dataframe:
# In[ ]:
def find_url(row):
text = str(re.sub('>', '', str(row)))
text = str(re.sub('<', '', text))
text = str(re.sub("'", '', text))
text = str(re.sub('"', '', text))
text = str(re.sub('^', '', text))
text = str(re.sub(';', '', text))
text = str(re.sub(r'\)', '', text))
text = str(re.sub(r'\[', '', text))
text = str(re.sub(r'\]', '', text))
text = str(re.sub(r'\n', ' ', text))
text = str(re.sub(r'\\', ' ', text))
text = str(re.sub(',', ' ', text))
# urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
urls = re.findall('http[s]?://hackmd.io/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
print(urls)
return (urls)
# Applying find_url function to the message texts and adding another column to the dataframe for URLs:
# In[ ]:
URL_df['URL'] = URL_df['text'].apply(find_url)
# Data cleaning for html pages: removing some characters from the text and split the data by comma
# In[ ]:
def str_clean(input):
output = str(input).replace('[', ',').replace(']', ',').replace("'", ',').replace('(', ',').replace(')', ',')
output = output.replace('<','').replace('>','').replace('"',',').replace('"', ',').replace(r"\\", ",")
output = output.split(r'\\|\n|\\\\|,')
return [output[i] for i in range(len(output)) if len(output[i]) > 2]# ignore words with length shorter than 3
# Loading url page content:
# In[ ]:
def visible(element):
if element.parent.name in ['style', 'style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element.encode('utf-8'))):
return False
return True
def url_loader(link):
urlBody = []
try:
html = urllib.request.urlopen(link, timeout=10)
except urllib.error.URLError as e:
html = None
return None
# except (HTTPError, URLError) as error:
except timeout:
html = None
return None
except requests.exception.InvalidURL:
html = None
return None
soup = BeautifulSoup(html)
data = soup.findAll(text=True)
result = filter(visible, data)
for element in result:
if len(element) > 1:
urlBody.append((element).strip())
urlBody = max(urlBody, key=len, default='Nan') if 'hackmd' in link else urlBody
cleanBody = str_clean(urlBody)
urls_in_body = find_url(str_clean(urlBody))
# print(urls_in_body)
return urls_in_body
# Loop over the URL column of the dataframe to pass the URLs to url_loader function and get list of urls from the page contents:
# In[ ]:
url_list = []
for i in range(URL_df['URL'].shape[0]):
temp = []
for l in URL_df['URL'].iloc[i]:
# print(l)
temp.append(url_loader(l))
url_list.append(temp)
# In[ ]:
URL_df['URL_b'] = url_list