-
Notifications
You must be signed in to change notification settings - Fork 0
/
ad_pop_functions.py
223 lines (186 loc) · 7.65 KB
/
ad_pop_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
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import json
import smtplib, ssl
from selenium.webdriver.common.keys import Keys
from flask import Flask, render_template, request, send_from_directory
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
app = Flask(__name__, template_folder='.', static_url_path='')
class Advertisment:
def __init__(self, ad_name, ad_url, ad_next_bounce, ad_status, num_watched, is_bounce_valid=False):
self.ad_name = ad_name
self.ad_url = ad_url
self.ad_next_bounce = ad_next_bounce
self.ad_status = ad_status
self.is_bounce_valid = is_bounce_valid
self.num_watched = num_watched
def print_me(self):
print("ad name: "+self.ad_name.__str__())
print("ad url: "+self.ad_url.__str__())
print("next bounce: "+self.ad_next_bounce.__str__())
print("is_bouncable: "+self.is_bounce_valid.__str__())
print("ad status: "+self.ad_status.__str__())
def login_to_yad2(username, password):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
browser = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
# browser = webdriver.Chrome("chromedriver75win")
browser.get("https://yad2.co.il/login.php")
if not browser.current_url == "https://my.yad2.co.il/login.php":
return browser
user_elem = browser.find_element_by_id("userName")
pass_elem = browser.find_element_by_id("password")
user_elem.send_keys(username)
pass_elem.send_keys(password)
pass_elem.send_keys(Keys.ENTER)
return browser
def get_active_categories_url(browser):
active_categories_urls = []
active_categories_elements = browser.find_elements_by_xpath("//a[@target='_self']")
for category in active_categories_elements:
active_categories_urls.append(category.get_attribute("href"))
return active_categories_urls
def get_next_bounce_time(browser):
desc = browser.find_element_by_xpath("//div[@class='desc orange']").text
match = re.search('([0-9][0-9]:[0-9][0-9])', desc)
time = ""
if match:
time = match.group(1)
return time
def get_ad_name(browser):
try:
ad_name = browser.find_element_by_id("info_title").text
except:
ad_name = browser.find_element_by_id("info").text
ad_name = ad_name[ad_name.find(":")+1:].strip()
return ad_name
def get_num_watched(browser):
try:
num_watched = browser.find_element_by_xpath('//*[@id="exposureResetTotal"]').get_attribute("value")
except:
num_watched = 0
return num_watched
def rerun_expired_ad(browser, ad_url):
browser.get(ad_url)
expired_msg_xpath = "//div[@class='desc orange']/div[@class='expired_msg']/a[@href]"
expired_url = browser.find_element_by_xpath(expired_msg_xpath).get_attribute('href')
if not expired_url:
return [browser, False]
browser.get(expired_url)
browser.get(ad_url)
return [browser, True]
def pop_active_ad(browser, ad_url):
browser.get(ad_url)
bounce_btn = browser.find_element_by_xpath("//*[@id='bounceRatingOrderBtn']")
if not bounce_btn:
return [browser, False]
bounce_btn.click()
return [browser, True]
def get_ads_from_category_url(browser, category_url, ads):
browser.get(category_url)
ads_url_element = browser.find_elements_by_xpath("//*[@id='feed']/tbody/tr[@data-frame]")
ads_details_element = browser.find_elements_by_xpath("//*[@id='feed']/tbody/tr[@class='item item-color-1']/td[contains(@class, 'status_wrapper')]/div")
url_and_status = []
for i in range(0, len(ads_url_element)):
url = "http:"+ads_url_element[i].get_attribute("data-frame")
status = ads_details_element[i].text
url_and_status.append((url, status))
for ad_url, ad_status in url_and_status:
browser.get(ad_url)
if "מודעה פעילה" in ad_status:
next_bounce_time = get_next_bounce_time(browser)
is_bouncable = False if next_bounce_time else True
else:
next_bounce_time = ""
is_bouncable = False
ad_name = get_ad_name(browser)
num_watched = get_num_watched(browser)
ad = Advertisment(ad_name, ad_url, next_bounce_time, ad_status, num_watched, is_bouncable)
ads[str(len(ads))] = ad.__dict__
def send_email(ads,reciver_email):
smtp_server = "smtp.gmail.com"
port = 587 # For starttls
sender_email = "popmyads2@gmail.com"
password = "Bbamba!YAD2"
context = ssl.create_default_context()
subject = "אל תדאג נשמה של ברבור הקפצנו לך!"
ad = ""
for url, add_prop in ads.items():
ad = u' '.join((ad, "מודעתך \""))
ad = u' '.join((ad, add_prop[3]))
ad = u' '.join((ad, "\" הוקפצה"))
ad = u' '.join((ad, "בכתובת"))
ad = u' '.join((ad, url))
ad = u' '.join((ad, "\n\n"))
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, password)
msg = "Subject: {}\n\n{}".format(subject, ad)
server.sendmail(sender_email, reciver_email, msg.encode('utf-8'))
except Exception as e:
print(e)
return "False"
server.quit()
return "True"
@app.route('/pop_ads', methods=['POST'])
def pop_ads():
advertisements = request.form['advertisements']
username = request.form['username']
password = request.form['password']
need_to_send_email = (request.form['send_email'] == "true")
advertisements = json.loads(advertisements)
if not advertisements:
return "{}"
browser = login_to_yad2(username, password)
for ad_url, status in advertisements.items():
browser.get(ad_url)
if status == "מודעה פעילה":
browser, pop_succeeded = pop_active_ad(browser, ad_url)
else:
browser, pop_succeeded = rerun_expired_ad(browser, ad_url)
next_bounce = get_four_hours_from_now()
ad_name = get_ad_name(browser)
advertisements[ad_url] = [status, next_bounce, pop_succeeded, ad_name]
if need_to_send_email:
send_email(advertisements, username)
browser.close()
return json.dumps(advertisements)
def create_ad_dict(browser):
active_categories_url = get_active_categories_url(browser)
ads = {}
for category_url in active_categories_url:
get_ads_from_category_url(browser, category_url, ads)
return ads
def get_four_hours_from_now():
import datetime
current_dt = datetime.datetime.now()
hours = str((current_dt.hour+4) % 24)
minutes = str(current_dt.minute)
return hours+":"+minutes
@app.route("/")
@app.route("/index.html")
def index():
return render_template('index.html')
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/main', methods=['POST'])
def main():
user_name = request.form['username']
password = request.form['password']
browser = login_to_yad2(user_name, password)
advertisements = create_ad_dict(browser)
browser.close()
return advertisements
if __name__ == "__main__":
app.debug = True
# app.run(host = '0.0.0.0',port=80)
app.run()