-
Notifications
You must be signed in to change notification settings - Fork 0
/
05_google_trends_2.py
149 lines (132 loc) · 4.76 KB
/
05_google_trends_2.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
import pytrends, io, sqlite3, urllib, time, datetime, csv, os, random, sys
from pytrends.request import TrendReq
from datetime import timedelta
import pandas as pd
from datetime import date
from datetime import datetime
from pytrends import *
from z_trends_prepare import create_db_and_folder
from dotenv import load_dotenv
load_dotenv()
create_db_and_folder()
file_kw = os.environ.get("file_kw_trend")
output_files = os.environ.get("output_files_trend")
file_name = os.environ.get("file_name_trend")
file_proxies = os.environ.get("file_proxies")
db_name_keyword = os.environ.get("db_name_keyword")
db_name_proxy = os.environ.get("db_name_proxy")
timestr = time.strftime('%Y%m%d-%H%M%S')
def select_proxy():
conn = sqlite3.connect(db_name_proxy)
c = conn.cursor()
data = pd.read_sql_query(
"SELECT PROXY FROM PROXY_LIST WHERE TIME = ( SELECT MIN(TIME) FROM PROXY_LIST);", conn)
# print(type(data['PROXY'].iat[0]))
global proxy
proxy = (data['PROXY'].iat[0])
print(f'---------------------Request IP is {proxy}')
timestr_now = str(datetime.now())
# print(timestr_now)
# global timestr
timestr = datetime.fromisoformat(timestr_now).timestamp()
# print(timestr)
c.execute("Update PROXY_LIST set TIME = ? where PROXY = ?", (timestr, proxy))
conn.commit()
c.execute("Update PROXY_LIST set TIME = ? where PROXY = ?",
(timestr, proxy,))
conn.commit()
# print('pausa 1 sec')
conn.close()
def select_keyword():
print('-------------------------')
conn = sqlite3.connect(db_name_keyword)
c = conn.cursor()
data = pd.read_sql_query(
"SELECT KEYWORDS FROM KEYWORDS_LIST WHERE SUM <> 2 AND CHECKING = 0 LIMIT 1;", conn)
# print(type(data['KEYWORDS'].iat[0]))
global keyword
keyword = (data['KEYWORDS'].iat[0])
c.execute("Update KEYWORDS_LIST set CHECKING = 1 where KEYWORDS = ?", (keyword,))
conn.commit()
conn.close()
# print(new_keyword)
def check_record_db():
conn = sqlite3.connect(db_name_keyword)
c = conn.cursor()
data = pd.read_sql_query("SELECT KEYWORDS FROM KEYWORDS_LIST WHERE SUM <> 2 AND CHECKING = 0 ;", conn)
global numbers_kw
numbers_kw = len(data)
print(numbers_kw)
conn.commit()
conn.close()
#
#
# Trend di ricerche nel tempo
#
#
check_record_db()
while numbers_kw != 0:
select_keyword()
select_proxy()
print(f'keyword ------- {keyword}')
single_search=keyword
dataset = []
proxies = []
proxies.append(proxy)
print(proxies)
kw_list = []
kw_list.append(keyword)
print(kw_list)
# print(keyword)
# pytrend = TrendReq(hl='it-IT', tz=360)
try:
pytrend =TrendReq(hl='it-IT', tz=360, timeout=(10,25), proxies=proxies, retries=10, backoff_factor=0.1)#, requests_args={'verify':False})
except:
conn = sqlite3.connect(db_name_keyword)
c = conn.cursor()
c.execute("Update KEYWORDS_LIST set CHECKING = 0 where KEYWORDS = ?",(keyword,))
conn.commit()
conn = sqlite3.connect(db_name_proxy)
c = conn.cursor()
print('---------------------Proxy da posticipare '+proxy)
postpone_time = str(datetime.now() + timedelta(hours=2))
timestr_postpone = datetime.fromisoformat(postpone_time).timestamp()
c.execute("Update PROXY_LIST set TIME = ? where PROXY = ?",(timestr_postpone,proxy))
conn.commit()
conn.close()
sys.exit()
pytrend.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='IT', gprop='')
data = pytrend.interest_over_time()
# print(data)
if not data.empty:
# data.drop(labels=['isPartial'], axis='columns')
data = data.drop(labels=['isPartial'],axis='columns')
dataset.append(data)
check_record_db()
try:
result = pd.concat(dataset, axis=1)
# print(result.info())
# print(result)
timestr = time.strftime('%Y%m%d-%H')
check_record_db()
if os.path.isfile(f'output_data/08_google_trends_2_{timestr}.csv'):
df_file = pd.read_csv(f'output_data/08_google_trends_2_{timestr}.csv', sep='\t', index_col='date')
# print(df_file)
# print(df_file.info())
df_file.index = df_file.index.astype(str)
df_file.index = df_file.index.str.replace(' 00:00:00', '')
# new_result = pd.concat([df_file,result], axis=1)
result.index = result.index.astype(str)
result.index = result.index.str.replace(' 00:00:00', '')
new_result = pd.concat([df_file,result], axis=1)
# print(new_result.info())
new_result.to_csv(f'output_data/08_google_trends_2_{timestr}.csv', sep='\t')
print('--------------DataFrame concatenato')
check_record_db()
else:
result.to_csv(f'output_data/08_google_trends_2_{timestr}.csv', sep='\t')
print('--------------DataFrame scritto')
check_record_db()
except:
print('--------------DataFrame VUOTO')
check_record_db()