-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
83 lines (60 loc) · 2.05 KB
/
functions.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
import psycopg2
import re
import requests
import urllib
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import pandas as pd
with open('Authentication/database_uri.txt', 'r', encoding="utf8") as f:
uri = f.read()
def setUpDB(command, url):
""" create tables in the PostgreSQL database"""
try:
# connect to the PostgreSQL server
conn = psycopg2.connect(url, sslmode='require')
cur = conn.cursor()
# create table one by one
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
conn.close()
# print('done')
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def getData(command, url):
conn = psycopg2.connect(url, sslmode='require')
try:
df = pd.read_sql(command, conn)
if conn is not None:
conn.close()
return df
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def getLinks(string):
urls = re.findall("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", string)
links = ''
for url in urls:
try:
opener = urllib.request.build_opener()
request = urllib.request.Request(url)
response = opener.open(request)
actual_url = response.geturl()
if '](' in actual_url:
actual_url = actual_url.split('](')[0]
links += actual_url + ';'
except:
if '](' in url:
url = url.split('](')[0]
links += url + ';'
return links
def getURLfromList(url):
if ';' in url:
url = url.split(';')[:-1]
result = []
for i in url:
result.append(urlparse(i).hostname)
return result
else:
return ''