source: phonelux_scrappers/scrappers/handy_scrapper.py@ 47f4eaf

Last change on this file since 47f4eaf was 47f4eaf, checked in by Marko <Marko@…>, 2 years ago

Final features implemented

  • Property mode set to 100644
File size: 6.3 KB
Line 
1import json
2import traceback
3import unicodedata
4from datetime import datetime
5import psycopg2
6import config_read
7from bs4 import BeautifulSoup
8from selenium import webdriver
9import requests
10
11import sys
12
13from classes.phoneoffer import PhoneOffer
14
15file_path = 'outputfile.txt'
16sys.stdout = open(file_path, "w")
17
18
19offer_shop = "Handy" # offer shop
20last_updated = datetime.now().date()
21is_validated = False
22
23# Call to read the configuration file and connect to database
24cinfo = config_read.get_databaseconfig("../postgresdb.config")
25db_connection = psycopg2.connect(
26 database=cinfo[0],
27 host=cinfo[1],
28 user=cinfo[2],
29 password=cinfo[3]
30)
31cur = db_connection.cursor()
32
33try:
34 # Handy phone offers that are already in database
35 offers = json.loads(unicodedata.normalize('NFKD', requests.get('http://localhost:8080/phoneoffer/shop/handy').text))
36
37 database_offers = []
38
39 for offer in offers:
40 phoneOffer = PhoneOffer(offer['id'], offer['offer_shop'], offer['offer_name'], offer['price'],
41 offer['ram_memory'],
42 offer['rom_memory'], offer['color'], offer['front_camera'], offer['back_camera'],
43 offer['chipset'], offer['battery'], offer['operating_system'], offer['cpu'],
44 offer['image_url'],
45 offer['offer_url'], offer['last_updated'], offer['is_validated'],
46 offer['offer_description'],
47 offer['offer_shop_code'])
48 database_offers.append(phoneOffer)
49
50 new_offers = []
51
52 handy_url = 'https://www.handy.mk/telefoni?page=6'
53
54 response1 = requests.get(handy_url)
55 soup1 = BeautifulSoup(response1.content, 'html.parser')
56
57 phones = soup1.find_all('li', {'data-hook': 'product-list-grid-item'})
58
59 for phone in phones:
60 offer_url = phone.find('a').get('href')
61 offer_name = phone.find('div', {'data-hook': 'not-image-container'})\
62 .find('h3', {'data-hook': 'product-item-name'}).get_text().strip()
63 brand = offer_name.split(' ')[0].capitalize()
64 price = int(float(phone.find('div', {'data-hook': 'not-image-container'}).find('div', {'data-hook': "product-item-product-details"})\
65 .find('span', {'data-hook': 'product-item-price-to-pay'}).get_text().strip().replace('ден', '').replace('.', '').replace(',', '.')))
66
67 response2 = requests.get(offer_url)
68 soup2 = BeautifulSoup(response2.text, 'html.parser')
69
70 back_camera = None
71 operating_system = None
72 chipset = None
73 battery = None
74 ram_memory = None
75 rom_memory = None
76 cpu = None
77 front_camera = None
78 offer_shop_code = None
79 color = None
80 image_url = None
81
82 color_section = soup2.find('section', {'data-hook': 'product-colors-title-section'})
83 if color_section is not None:
84 temp_colors = color_section.find('fieldset', {'class': 'ColorPickerbase3548966286__container'})\
85 .find_all('input', {'type': 'radio'})
86 colors_list = []
87 for temp_color in temp_colors:
88 colors_list.append(temp_color.get('aria-label'))
89 color = ','.join(colors_list)
90
91 rows = soup2.find('div', {'data-hook': 'info-section-description'}).find_all('li')
92
93 if len(rows) == 0:
94 rows = soup2.find('div', {'data-hook': 'info-section-description'}).find_all('tr')
95
96 specifications = []
97
98 for row in rows:
99 specifications.append(unicodedata.normalize('NFKD', row.get_text().strip()))
100
101 offer_description = '\n'.join(specifications)
102
103 new_offers.append(PhoneOffer(offer_shop, offer_name, price, ram_memory, rom_memory,
104 color, front_camera, back_camera, chipset, battery, operating_system, cpu,
105 image_url,
106 offer_url, last_updated, is_validated, offer_description, offer_shop_code))
107
108 for new_offer in new_offers:
109 flag = False
110 flag_price = False
111 offer_id = None
112
113 for old_offer in database_offers:
114
115 if new_offer.offer_name == old_offer.offer_name:
116 flag = True
117 if new_offer.price != old_offer.price:
118 flag_price = True
119 offer_id = old_offer.offer_id
120
121 if flag:
122 # print('ALREADY IN DATABASE')
123 # print(new_offer)
124 # if it's already in database, check PRICE and if it's changed, change it !!!!!!
125 if flag_price:
126 print('PRICE CHANGED!') # CHANGE PRICE
127 print('offer id: ' + str(offer_id))
128 headers = {'Content-type': 'application/json'}
129 requests.put('http://localhost:8080/phoneoffer/' + str(offer_id) + '/changeprice/' + str(new_offer.price),
130 headers=headers)
131 else:
132 print('ADDED') # ADD OFFER
133 print(new_offer)
134 headers = {'Content-type': 'application/json'}
135 requests.post('http://localhost:8080/phoneoffer/addoffer',
136 headers=headers, data=json.dumps(new_offer.__dict__, default=str))
137
138 print('------------------------------------')
139
140 for old_offer in database_offers:
141 flag = False
142 for new_offer in new_offers:
143 if old_offer.offer_name == new_offer.offer_name:
144 flag = True
145
146 if not flag:
147 print('OFFER DELETED')
148 print(old_offer)
149 # DELETE OFFER
150 requests.delete('http://localhost:8080/phoneoffer/deleteoffer/' + str(old_offer.offer_id))
151except Exception:
152 traceback.print_exc()
153 insert_script = 'INSERT INTO scrapper_info (store, recieved_at, status)' \
154 ' VALUES (%s, %s, %s);'
155 insert_value = (offer_shop, last_updated, 'failed')
156 cur.execute(insert_script, insert_value)
157 db_connection.commit()
158 cur.close()
159 db_connection.close()
160else:
161 insert_script = 'INSERT INTO scrapper_info (store, recieved_at, status)' \
162 ' VALUES (%s, %s, %s);'
163 insert_value = (offer_shop, last_updated, 'success')
164 cur.execute(insert_script, insert_value)
165 db_connection.commit()
166 cur.close()
167 db_connection.close()
168
169
170
Note: See TracBrowser for help on using the repository browser.