1 | import json
|
---|
2 | import traceback
|
---|
3 | import unicodedata
|
---|
4 | from datetime import datetime
|
---|
5 | import psycopg2
|
---|
6 | import config_read
|
---|
7 | from bs4 import BeautifulSoup
|
---|
8 | from selenium import webdriver
|
---|
9 | import requests
|
---|
10 | import sys
|
---|
11 |
|
---|
12 | from classes.phoneoffer import PhoneOffer
|
---|
13 |
|
---|
14 | file_path = 'outputfile.txt'
|
---|
15 | sys.stdout = open(file_path, "w")
|
---|
16 |
|
---|
17 |
|
---|
18 | def scrape_function(driver1, i, new_offers):
|
---|
19 | offer_shop = "Tehnomarket" # offer shop
|
---|
20 | last_updated = datetime.now().date()
|
---|
21 | is_validated = False
|
---|
22 |
|
---|
23 | tehnomarket_html = driver1.page_source
|
---|
24 | soup1 = BeautifulSoup(tehnomarket_html, 'html.parser')
|
---|
25 | active_li = soup1.find('div', {'class': 'adjust-elems pagination pagination-centered'}).find('li',
|
---|
26 | {'class': 'active'})
|
---|
27 |
|
---|
28 | print('page: ' + active_li.get_text())
|
---|
29 |
|
---|
30 | if int(active_li.get_text().strip()) == i:
|
---|
31 | phones = soup1.find('ul', {'class': 'products products-display-grid thumbnails'}).find_all('li', {
|
---|
32 | 'class': 'span4 product-fix'})
|
---|
33 |
|
---|
34 | for phone in phones:
|
---|
35 | offer_url = phone.find('a').get('href')
|
---|
36 | offer_name = phone.find('div', {'class': 'product-name'}).get_text().strip()
|
---|
37 | price = int(phone.find('div', {'class': 'product-price clearfix'}).find('strong') \
|
---|
38 | .get_text().replace('ден.', '').replace(',', '').strip())
|
---|
39 |
|
---|
40 | response2 = requests.get(offer_url)
|
---|
41 | soup2 = BeautifulSoup(response2.content, 'html.parser')
|
---|
42 |
|
---|
43 | image = soup2.find('div', {'id': 'product_gallery'}).find('img')
|
---|
44 |
|
---|
45 | image_url = None
|
---|
46 | if image is not None:
|
---|
47 | image_url = image.get('src')
|
---|
48 |
|
---|
49 | details = soup2.find('div', {'class': 'product-desc'}).get_text().split('\n')
|
---|
50 |
|
---|
51 | brand = details[2].strip().capitalize()
|
---|
52 | offer_shop_code = details[4].strip()
|
---|
53 |
|
---|
54 | back_camera = None
|
---|
55 | operating_system = None
|
---|
56 | chipset = None
|
---|
57 | battery = None
|
---|
58 | ram_memory = None
|
---|
59 | rom_memory = None
|
---|
60 | cpu = None
|
---|
61 | front_camera = None
|
---|
62 | color = None
|
---|
63 |
|
---|
64 | specifications = []
|
---|
65 | for info in soup2.find_all('span', {'class': 'info'}):
|
---|
66 | specifications.append(info.get_text())
|
---|
67 |
|
---|
68 | offer_description = '\n'.join(specifications)
|
---|
69 |
|
---|
70 | new_offers.append(PhoneOffer(offer_shop, offer_name, price, ram_memory, rom_memory,
|
---|
71 | color, front_camera, back_camera, chipset, battery, operating_system, cpu,
|
---|
72 | image_url,
|
---|
73 | offer_url, last_updated, is_validated, offer_description, offer_shop_code))
|
---|
74 | else:
|
---|
75 | driver1.implicitly_wait(30)
|
---|
76 | scrape_function(driver1, i, new_offers)
|
---|
77 |
|
---|
78 |
|
---|
79 | # Call to read the configuration file and connect to database
|
---|
80 | cinfo = config_read.get_databaseconfig("../postgresdb.config")
|
---|
81 | db_connection = psycopg2.connect(
|
---|
82 | database=cinfo[0],
|
---|
83 | host=cinfo[1],
|
---|
84 | user=cinfo[2],
|
---|
85 | password=cinfo[3]
|
---|
86 | )
|
---|
87 | cur = db_connection.cursor()
|
---|
88 |
|
---|
89 | try:
|
---|
90 | # Tehnomarket phone offers that are already in database
|
---|
91 | offers = json.loads(
|
---|
92 | unicodedata.normalize('NFKD', requests.get('http://localhost:8080/phoneoffer/shop/tehnomarket').text))
|
---|
93 |
|
---|
94 | database_offers = []
|
---|
95 |
|
---|
96 | for offer in offers:
|
---|
97 | phoneOffer = PhoneOffer(offer['id'], offer['offer_shop'], offer['offer_name'], offer['price'],
|
---|
98 | offer['ram_memory'],
|
---|
99 | offer['rom_memory'], offer['color'], offer['front_camera'], offer['back_camera'],
|
---|
100 | offer['chipset'], offer['battery'], offer['operating_system'], offer['cpu'],
|
---|
101 | offer['image_url'],
|
---|
102 | offer['offer_url'], offer['last_updated'], offer['is_validated'],
|
---|
103 | offer['offer_description'],
|
---|
104 | offer['offer_shop_code'])
|
---|
105 | database_offers.append(phoneOffer)
|
---|
106 |
|
---|
107 | new_offers = []
|
---|
108 |
|
---|
109 | for i in range(1, 6):
|
---|
110 | tehnomarket_url = 'https://tehnomarket.com.mk/category/4109/mobilni-telefoni#page/' + str(i)
|
---|
111 | # print(anhoch_url)
|
---|
112 |
|
---|
113 | # selenium is used because of the dynamic content of the page
|
---|
114 | driver1 = webdriver.Safari(executable_path='/usr/bin/safaridriver')
|
---|
115 | driver1.get(tehnomarket_url)
|
---|
116 |
|
---|
117 | scrape_function(driver1, i, new_offers)
|
---|
118 |
|
---|
119 | # closing the driver so the safari instance can pair with another webdriver session
|
---|
120 | driver1.close()
|
---|
121 |
|
---|
122 | for new_offer in new_offers:
|
---|
123 | flag = False
|
---|
124 | flag_price = False
|
---|
125 | offer_id = None
|
---|
126 |
|
---|
127 | for old_offer in database_offers:
|
---|
128 |
|
---|
129 | if new_offer.offer_shop_code == old_offer.offer_shop_code:
|
---|
130 | flag = True
|
---|
131 | if new_offer.price != old_offer.price:
|
---|
132 | flag_price = True
|
---|
133 | offer_id = old_offer.offer_id
|
---|
134 |
|
---|
135 | if flag:
|
---|
136 | # print('ALREADY IN DATABASE')
|
---|
137 | # print(new_offer)
|
---|
138 | # if it's already in database, check PRICE and if it's changed, change it !!!!!!
|
---|
139 | if flag_price:
|
---|
140 | print('PRICE CHANGED!') # CHANGE PRICE
|
---|
141 | print('offer id: ' + str(offer_id))
|
---|
142 | headers = {'Content-type': 'application/json'}
|
---|
143 | requests.put('http://localhost:8080/phoneoffer/' + str(offer_id) + '/changeprice/' + str(new_offer.price),
|
---|
144 | headers=headers)
|
---|
145 | else:
|
---|
146 | print('ADDED') # ADD OFFER
|
---|
147 | print(new_offer)
|
---|
148 | headers = {'Content-type': 'application/json'}
|
---|
149 | requests.post('http://localhost:8080/phoneoffer/addoffer',
|
---|
150 | headers=headers, data=json.dumps(new_offer.__dict__, default=str))
|
---|
151 |
|
---|
152 | print('------------------------------------')
|
---|
153 |
|
---|
154 | for old_offer in database_offers:
|
---|
155 | flag = False
|
---|
156 | for new_offer in new_offers:
|
---|
157 | if old_offer.offer_shop_code == new_offer.offer_shop_code:
|
---|
158 | flag = True
|
---|
159 |
|
---|
160 | if not flag:
|
---|
161 | print('OFFER DELETED')
|
---|
162 | print(old_offer)
|
---|
163 | # DELETE OFFER
|
---|
164 | requests.delete('http://localhost:8080/phoneoffer/deleteoffer/' + str(old_offer.offer_id))
|
---|
165 | except Exception:
|
---|
166 | traceback.print_exc()
|
---|
167 | insert_script = 'INSERT INTO scrapper_info (store, recieved_at, status)' \
|
---|
168 | ' VALUES (%s, %s, %s);'
|
---|
169 | insert_value = ('Tehnomarket', datetime.now().date(), 'failed')
|
---|
170 | cur.execute(insert_script, insert_value)
|
---|
171 | db_connection.commit()
|
---|
172 | cur.close()
|
---|
173 | db_connection.close()
|
---|
174 | else:
|
---|
175 | insert_script = 'INSERT INTO scrapper_info (store, recieved_at, status)' \
|
---|
176 | ' VALUES (%s, %s, %s);'
|
---|
177 | insert_value = ('Tehnomarket', datetime.now().date(), 'success')
|
---|
178 | cur.execute(insert_script, insert_value)
|
---|
179 | db_connection.commit()
|
---|
180 | cur.close()
|
---|
181 | db_connection.close()
|
---|