-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookiepedia.py
190 lines (155 loc) · 5.11 KB
/
cookiepedia.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
from email import header
import sys
from DBOps import DBOps
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import os
import tldextract
from urllib.parse import urlparse, unquote
import random
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import (
MoveTargetOutOfBoundsException,
TimeoutException,
WebDriverException,
)
import multiprocessing
from google.cloud import bigquery
thread_count = 10
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.getcwd() + \
'/resources/google.json'
client = bigquery.Client()
def getSeleniumProfilePath():
import tempfile
dirpath = tempfile.mkdtemp()
return dirpath
path = ''
if os.name == 'nt':
path = os.getcwd() + '/profiles/chrome/main_commander/'
else:
path = os.getcwd() + '/profiles/chrome/main_commander/'
return path
def loadBrowser():
xoptions = webdriver.ChromeOptions()
xoptions.add_argument("--log-level=3")
profile_path = getSeleniumProfilePath()
print(profile_path)
xoptions.add_argument("user-data-dir=" + profile_path)
# options.page_load_strategy = 'none'
xoptions.add_argument("no-sandbox")
xoptions.add_argument("disable-gpu")
xoptions.add_argument("disable-browser-side-navigation ")
xoptions.add_argument("headless")
driver = webdriver.Chrome(
executable_path=getDriverPath(), options=xoptions)
driver.find_element
return driver, profile_path
def getDriverPath():
path = ''
if os.name == 'nt':
path = os.getcwd() + '/drivers/chromedriver.exe'
else:
path = os.getcwd() + '/drivers/chromedriver'
return path
def start():
query_tracker = """SELECT
DISTINCT(name)
FROM
cookies.cookies
WHERE
name NOT IN (
SELECT
name
FROM
`ifis-web-measurements.cookies.cookies_cat_processed`)"""
query_job = client.query(query_tracker)
try:
rows = query_job.result().to_dataframe().values.tolist()
print('query data loaded.')
except Exception as e:
print(e)
print('error')
totalRow = len(rows)
print("Total Rows: ", totalRow)
avarageRows = int(totalRow/thread_count)
splittedRows = []
for i in range(thread_count):
if i == len(range(thread_count))-1:
splittedRows.append(rows)
else:
splittedRows.append(rows[0:avarageRows])
del rows[0:avarageRows]
print("splittedRows count: " + str(len(splittedRows)))
print("row count: " + str(len(rows)))
for item in splittedRows:
p1 = multiprocessing.Process(
target=doAnalyse, args=(item,))
p1.start()
def doAnalyse(rows):
cookieList = []
for item in rows:
cookie = {}
cookie['name'] = item[0]
cookie['cat'] = getCat(item[0])
cookieList.append(cookie)
print(cookie)
if len(cookieList) == 50:
pushRows('cookies.cookies_cat_processed', cookieList)
cookieList = []
def getCat(name):
import requests
import re
url = "https://cookiepedia.co.uk/cookies/"
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
full_url = url + name
req = requests.get(full_url, headers=headers)
if req.status_code != 200:
pass
lbl_cat = ''
response = req.content.decode('utf8')
if response.find('<strong>Strictly Necessary</strong>') != -1:
lbl_cat = "Strictly Necessary"
if response.find('<strong>Targeting/Advertising</strong>') != -1:
lbl_cat = "Targeting/Advertising"
if response.find('<strong>Unknown</strong>') != -1:
lbl_cat = "Unknown"
if response.find('<strong>Functionality</strong>') != -1:
lbl_cat = "Functionality"
if response.find('<strong>Performance</strong>') != -1:
lbl_cat = "Performance"
return lbl_cat
"""
cat = re.search(
"The main purpose of this cookie is: <strong>([a-zA-Z]*( [a-zA-Z]*)*)</strong>", response)
print(cat)
if cat:
return cat.group(1)
else:
return ''
"""
def pushRows(p_tableID, p_rows, p_timeout=60):
table_id = p_tableID
try:
errors = client.insert_rows_json(table_id, p_rows, timeout=p_timeout)
if errors == []:
print('pushed rows to BigQuery:' +
p_tableID + ': ' + str(len(p_rows)))
else:
raise Exception(
p_tableID + ": Encountered errors while inserting rows: {}".format(errors))
except:
print('error while pushing.. retry..')
errors = client.insert_rows_json(table_id, p_rows, timeout=30)
if errors == []:
print('pushed rows to BigQuery:' +
p_tableID + ': ' + str(len(p_rows)))
else:
raise Exception(
p_tableID + ": Encountered errors while inserting rows: {}".format(errors))
if __name__ == "__main__":
start()
# print(getCat('MUID'))