-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_reviews.py
172 lines (118 loc) · 5.61 KB
/
google_reviews.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
import time,csv
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException,WebDriverException
from datetime import datetime
from dateutil.relativedelta import relativedelta
def google_reviews(URL):
def time_converter(date: str):
current_time = datetime.now()
date = date.split(' ')[1:]
if 'un' in date or 'una' in date:
date[0] = 1
else:
date[0]=int(date[0])
if date[1] == 'día' or date[1] == 'días':
relative_time = relativedelta(days=date[0])
if date[1] == 'mes' or date[1] == 'meses':
relative_time = relativedelta(months=date[0])
if date[1] == 'semana' or date[1] == 'semanas':
relative_time = relativedelta(weeks=date[0])
if date[1] == 'año' or date[1] == 'años':
relative_time = relativedelta(years=date[0])
new_time = current_time - relative_time
formatted_date = new_time.strftime("%Y-%m-%d")
return formatted_date
def get_data(driver):
count=1
print('getting data... please wait')
more_elements = driver.find_elements(By.CLASS_NAME, 'w8nwRe.kyuRq')
for list_more_element in more_elements:
list_more_element.click()
elements = driver.find_elements(By.CLASS_NAME,'jftiEf')
lst_data = [ ]
for data in elements:
try:
#name = data.find_element(By.CLASS_NAME, 'd4r55 ').text
user = f'user_{count}'
text = data.find_element(By.CLASS_NAME, 'wiI7pd').text
time=data.find_element(By.CLASS_NAME,'rsqaWe').text
date = time_converter(time)
score = data.find_element(By.CLASS_NAME,'kvMYJc').get_attribute("aria-label")
except NoSuchElementException:
text = "Text Null"
lst_data.append([user, text, time, date, score]) # name
#print(len(lst_data),' row is generated')
count+=1
return lst_data
def counter(tittle):
#deprecated: result = driver.find_element_by_class_name('jANrlb').find_element_by_class_name('fontBodySmall').text
result = driver.find_element(By.CLASS_NAME,'jANrlb').text
rating = result[:3]
result = result.split('\n')[1].split(' ')
result = result[0]
print(f'{tittle} has {rating} and {result} reviews ')
if '.' in result:
result = int(result.replace('.', ''))
if result >=2500:
print("to many reviews to scroll... fetched to 200 scroll down ") # each scroll down takes 2 sec to wait comments to appears
result = 200
return result
return int((result / 10) + 1)
return int(int(result) / 10) + 1
def scrolling(counter):
print('scrolling over the reviews...')
scrollable_div = driver.find_element(By.XPATH,'//*[@id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[2]/div[11]/div')
for _i in range(counter):
#time.sleep(2)
try:
scrolling = driver.execute_script(
'document.getElementsByClassName("dS8AEf")[0].scrollTop = document.getElementsByClassName("dS8AEf")[0].scrollHeight',
scrollable_div, time.sleep(2))
except WebDriverException:
print('stop scrolling... ')
return
print("scrolling was complete")
# Scroll up
driver.execute_script('document.getElementsByClassName("dS8AEf")[0].scrollTop = 0')
def write_to_csv(data, tittle):
print('Writing to csv...')
cols = ['user_id', 'comment', 'time', 'date', 'rating']
df = pd.DataFrame(data, columns=cols)
df.to_csv(f'{tittle}_google_reviews.csv')
print("Your csv was successfully created!")
print('starting...')
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless") # show browser or not
chrome_options.add_argument("--lang=en-US")
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)
#Example
#URL = 'https://www.google.com/maps/place/El+Curry+Verde/@43.3769804,-1.8015808,17z/data=!3m1!4b1!4m6!3m5!1s0xd5109081bb759a1:0xc866b9f78bb1dc19!8m2!3d43.3769766!4d-1.7967152!16s%2Fg%2F1hc7nn793?entry=ttu'
#URL = input("Please, paste the url to get the reviews: ")
driver.get(URL)
time.sleep(3)
reject = driver.find_element(By.XPATH,'//*[@id="yDmH0d"]/c-wiz/div/div/div/div[2]/div[1]/div[3]/div[1]/div[1]/form[1]/div/div/button/span')
reject.click()
time.sleep(3)
header =driver.find_element(By.CLASS_NAME,'DUwDvf').text
reviews = driver.find_element(By.XPATH,'//*[@id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[3]/div/div/button[2]/div[2]/div[2]')
reviews.click()
counter = counter(header)
scrolling(counter)
data = get_data(driver)
driver.close()
write_to_csv(data,header)
"""
For the program works properly is necessary the link needs to be in the following form:
https://www.google.com/maps/place/El+Curry+Verde/@43.3769804,-1.8015808,17z/data=!3m1!4b1!4m6!3m5!1s0xd5109081bb759a1:0xc866b9f78bb1dc19!8m2!3d43.3769766!4d-1.7967152!16s%2Fg%2F1hc7nn793?entry=ttu
"""
def run_ggl():
question_mark =input("Do you want to download Google reviews? yes/no ")
if question_mark == 'yes':
URL = input("please paste google URL: ")
google_reviews(URL)
else:
with open('empty_list_csv', 'w') as f:
csv.writer(f)