[TOC]

Parsing a Property website in multiprocessing way

  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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# %%
import sqlite3
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import logging
from pathlib import Path
from tqdm.auto import tqdm
import os
import pickle
import csv
import time
import threading
from glob import glob
import argparse
import random

# %% [markdown]
# ## Multiprocessing version

# %%
from tqdm.contrib.concurrent import process_map, thread_map
from multiprocessing import Pool, Process, Manager, Lock
import multiprocessing as mp
from multiprocessing.dummy import Pool as DummyPool
from webdriver_manager.chrome import ChromeDriverManager
from logging.handlers import RotatingFileHandler
HEADLESS = False
VERSION = 120
PROCESS_NUM = 4
CHUNK_SIZE = 300
IMPLICIT_WAIT_TIME = 5


def setupLogger(loggername, loggingfile = None, logginglevel = logging.INFO, loggingqueue = None):
    """
    Set up a logger with the specified name and optional logging file.

    Parameters:
    loggername (str): The name of the logger.
    loggingfile (str): The path to the logging file (optional).

    Returns:
    logging.Logger: The configured logger.
    """
    if loggername not in logging.Logger.manager.loggerDict:
        # Create a logger in the main process
        logger = logging.getLogger(loggername)
        logger.setLevel(logginglevel)
        handler = logging.StreamHandler()
        if loggingfile is not None:
            filehandler = RotatingFileHandler(loggingfile, maxBytes=1000000, backupCount=3, delay=True)
            processname = mp.current_process().name
            if processname == 'MainProcess':
                # clear the log file
                with open(loggingfile, 'w'):
                    pass
        formatter = logging.Formatter('%(asctime)s [%(processName)s] [%(levelname)s] %(message)s')
        handler.setFormatter(formatter)
        filehandler.setFormatter(formatter)
        if loggingqueue is not None:
            queuehandler = logging.handlers.QueueHandler(loggingqueue)
            logger.addHandler(queuehandler)
        logger.addHandler(handler)
        if loggingfile is not None:
            logger.addHandler(filehandler)
        return logger
    else:
        return logging.getLogger(loggername)

class logging_tqdm(tqdm):
    def __init__(
            self,
            *args,
            loggername="logging_tqdm_logger",
            loggingfile = None,
            logginglevel = logging.INFO,
            loggingqueue = None,
            mininterval: float = 1,
            bar_format: str = '{desc}{percentage:3.0f}%{r_bar}',
            desc: str = 'progress: ',
            **kwargs):
        self._loggername = loggername
        self._loggingfile = loggingfile
        self._logginglevel = logginglevel
        self._loggingqueue = loggingqueue
        self._logger = setupLogger(loggername, loggingfile, logginglevel, loggingqueue)
        
        super().__init__(
            *args,
            mininterval=mininterval,
            bar_format=bar_format,
            desc=desc,
            **kwargs
        )

    @property
    def logger(self):
        if self._logger is not None:
            return self._logger
        return setupLogger(self._loggername, self._loggingfile, self._logginglevel, self._loggingqueue)

    def display(self, msg=None, pos=None):
        if not self.n:
            # skip progress bar before having processed anything
            return
        if not msg:
            msg = self.__str__()
        self.logger.info(f'%s', msg)

def sleepy_find_element(browser, by_query_list, attempt_count :int =30, sleep_duration =0.3):
    '''
    Finds the web element using the locator and query.

    This function attempts to find the element multiple times with a specified
    sleep duration between attempts. If the element is found, the function returns the element.

    Args:
        by (selenium.webdriver.common.by.By): The method used to locate the element.
        query (str): The query string to locate the element.
        attempt_count (int, optional): The number of attempts to find the element. Default: 20.
        sleep_duration (int, optional): The duration to sleep between attempts. Default: 1.

    Returns:
        selenium.webdriver.remote.webelement.WebElement: Web element or None if not found.
    '''
    if not isinstance(by_query_list[0], (list, tuple)):
        by_query_list = [by_query_list]
    item = []
    browser.implicitly_wait(0.3)
    for _count in range(attempt_count):
        for (by, query) in by_query_list:
            item = browser.find_elements(by, query)
            if len(item) > 0:
                item = item[0]
                # logging.info(f'Element {query} has found')
                break
        if item == []: 
            # logging.info(f'Element {query} is not present, attempt: {_count+1}')
            time.sleep(sleep_duration)
        else:
            break 
    if item is list:
        logging.warning("Element not find!")
    browser.implicitly_wait(IMPLICIT_WAIT_TIME)
    return item

def collect_data_multiprocessing(postcode_chunk,
                                 chromelock,nodatalock,savedpstcdlock,loggingqueue,
                                 chrome_profile_path_lst,
                                 loggername,
                                 loggingfile,
                                 data_index
                                 ):
    import undetected_chromedriver as uc # local import due to memory leak
    
    # setuplogger 
    logger = setupLogger(loggername, loggingfile, loggingqueue=loggingqueue)
    saved_postcode_lst = []
    no_data_lst = []
    # variables 
    website_url = "https://propertydata.co.uk/internal-area-lookup"
    website_login_url = "https://propertydata.co.uk/login"
    postcode_input_xp = '//input[contains(@name, "postcode")]'
    submit_but_xp = '//input[contains(@name, "postcode")]/../following-sibling::label/input[contains(@type, "submit")]'
    back_but_xp = '//a[contains(.,"Look up another postcode")]'
    not_found_xp = '//p[contains(., "No energy performance")]'
    not_found_xp_2 = '//p[contains(., "enter a valid")]'
    anchor_td_xp = '//td[contains(., "Inspection date")]'
    data_tr_xp = anchor_td_xp + '/../../tr'
    # init browser
    with chromelock:
        chrome_profile_path = chrome_profile_path_lst.pop()
        logger.info(f"Chrome profile path: {chrome_profile_path}") # todo 
    options = uc.ChromeOptions()
    options.page_load_strategy = 'eager'
    # options.add_argument("--auto-open-devtools-for-tabs") # help to avoid cloudfare human verify check
    options.add_argument("--disable-popup-blocking")
    options.add_argument("--window-size=800,600")
    # options.add_argument("--start-maximized")
    # options.add_argument('--disable-gpu')
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-setuid-sandbox")
    options.add_argument("--disable-extensions")
    options.add_argument('--disable-application-cache')
    options.add_argument("--disable-dev-shm-usage")
    if HEADLESS:
        options.add_argument("--headless=new")

    driver = None 
    
    # get process name 
    thread_name = mp.current_process().name
    
    def init_and_login_localf():
        driver.get("https://www.google.com/")
        time.sleep(1)
        driver.get(website_url)
        time.sleep(1)
        acc_eles = sleepy_find_element(driver, (By.XPATH, '//a[@href ="/account"]'))
        if acc_eles == []:
            logger.warning("Try to ReLogin")
            try:
                driver.get(website_login_url)
            except TimeoutException as e:
                logger.error(f"{e}")
                logger.error("Cannot Open Login Page!!!!")
                raise e
            address_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "email")]'])
            address_ele.click()
            time.sleep(1)

            time.sleep(1)
            passwd_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "password")]'])
            passwd_ele.click()
            time.sleep(1)

            time.sleep(1)
            remember_me_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "remember")]'])
            remember_me_ele.click()
            submit_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@type, "submit")]'])
            submit_ele.click()
            WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]')))
            driver.get(website_url)
            WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]')))
        
    try:
        # check os system
        if os.name == "posix":
            time.sleep(0.3) # wait for chrome profile to be ready
            driver = uc.Chrome(options=options,
                            driver_executable_path=ChromeDriverManager().install(),
                            user_data_dir=chrome_profile_path,
                            # version_main=VERSION,
                            user_multi_procs=True)
        elif os.name == "nt":
            time.sleep(0.3) # wait for chrome profile to be ready
            # options.add_argument(f"--user-data-dir={chrome_profile_path}")
            driver = uc.Chrome(options=options,
                                driver_executable_path=ChromeDriverManager().install(),
                            #    driver_executable_path=os.path.join(os.path.abspath(os.getcwd()), 'chromedriver-win64/chromedriver-win64/chromedriver.exe'),
                               user_multi_procs=True,
                               )
        else:
            raise Exception("Unknown OS")
        driver.implicitly_wait(IMPLICIT_WAIT_TIME)
        the_id_num = int(chrome_profile_path.split("_")[-1])
        if the_id_num == 0:
            x_offset = 0
            y_offset = 0
        elif the_id_num == 1:
            x_offset = 750
            y_offset = 0
        elif the_id_num == 2:
            x_offset = 0
            y_offset = 450
        elif the_id_num == 3:
            x_offset = 750
            y_offset = 450
        else:
            x_offset = 0
            y_offset = 0
        driver.set_window_size(900, 700, windowHandle ='current')
        time.sleep(1.5)
        driver.set_window_position(random.randint(40,80) + x_offset, random.randint(40,80) + y_offset, windowHandle ='current')
        time.sleep(2.5)
        init_and_login_localf()
        
            
        # loop 
        for ind in tqdm(range(len(postcode_chunk)), desc="Working in "+thread_name):
            cur_postcode_name = postcode_chunk[ind]
            try:
                try_limit = 3
                try_count = 0
                while try_count < try_limit:
                    # load loopup result
                    time.sleep(0.3)
                    postcode_input_ele = sleepy_find_element(driver, [By.XPATH, postcode_input_xp])
                    submit_but_ele = sleepy_find_element(driver, [By.XPATH, submit_but_xp])
                    time.sleep(0.2)
                    postcode_input_ele.click()
                    postcode_input_ele.send_keys(cur_postcode_name)
                    time.sleep(1)
                    submit_but_ele.click()
                    # collect data 
                    # ancor_or_not_found_ele = WebDriverWait(driver, 30).until(EC.any_of(
                    #     EC.presence_of_element_located((By.XPATH, not_found_xp)),
                    #     EC.presence_of_element_located((By.XPATH, not_found_xp_2)),
                    #     EC.presence_of_element_located((By.XPATH, anchor_td_xp))
                    # ))
                    time.sleep(0.4)
                    ancor_or_not_found_ele = sleepy_find_element(driver, [(By.XPATH, anchor_td_xp),(By.XPATH, not_found_xp),
                                                                        (By.XPATH, not_found_xp_2),
                                                                        (By.XPATH, submit_but_xp)
                                                                        ], 20)
                    
                    if ancor_or_not_found_ele == []:
                        try_count += 1
                        continue
                    if ancor_or_not_found_ele.tag_name == 'input':
                        try_count += 1
                        continue
                    break
                ancor_or_not_found_ele = sleepy_find_element(driver, [(By.XPATH, anchor_td_xp),(By.XPATH, not_found_xp),
                                                                        (By.XPATH, not_found_xp_2),
                                                                        ], 20)
                if ancor_or_not_found_ele == []:
                    raise TimeoutException
             
                # check if no data
                elif ancor_or_not_found_ele.tag_name == 'p':
                    no_data_lst.append(cur_postcode_name)
                    if len(no_data_lst) > 0: # save to file 
                        with nodatalock:
                            with open('./running_input/postcode_no_data_lst.txt', 'a') as f:
                                for pcl in no_data_lst:
                                    f.write(str(pcl)+"\n")
                                no_data_lst[:] = [] # manager list remove all 
                    init_and_login_localf()
                    continue
                time.sleep(random.randint(4,8))
                # data_tr_eles =  WebDriverWait(driver, 2).until(
                #                 EC.presence_of_all_elements_located((By.XPATH, data_tr_xp)))
                data_tr_eles = driver.find_elements(By.XPATH, data_tr_xp)
                data_tr_eles = data_tr_eles[1:] # remove first row
            except (NoSuchElementException, TimeoutException) as e:
                # try to skip cloudflare
                # driver.execute_script('''window.open("http://nowsecure.nl","_blank");''') # open page in new tab
                try:
                    sleeptimeforcd = 30 
                    logger.warning(f"Blocked by {type(e)}, Try to Sleep {sleeptimeforcd}s.")
                    WebDriverWait(driver, sleeptimeforcd).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]')))
                except TimeoutException:
                    init_and_login_localf()
                continue 
            

        
            row_total_lst = []
            for temp_data_tr_ele in data_tr_eles:
                all_eles = temp_data_tr_ele.find_elements(By.XPATH, "./td")
                
                if len(all_eles) != 6:
                    continue 
                inspection_date = all_eles[0].text
                address = all_eles[1].text
                floor_area = all_eles[2].text
                habitable_room = all_eles[3].text
                energyrate = all_eles[4].text
                energyrate_val = all_eles[5].text
                irow = [inspection_date, address, floor_area, habitable_room, energyrate, energyrate_val, cur_postcode_name]
                row_total_lst.append(irow)
            # save to file 
                # with open("./postcode_lookup_info.csv", 'a') as f:
                #     wt = csv.writer(f)
                #     wt.writerows(row_total_lst)
                # we need database 
            conn = sqlite3.connect(f'./running_output/postcode_lookup_info.db')  
            curser = conn.cursor()
            with conn:
                sql_create_table = f""" CREATE TABLE IF NOT EXISTS postcode_info_data_table_{data_index} (
                                    inspection_date TEXT,
                                    address TEXT UNIQUE,
                                    floor_area TEXT,
                                    habitable_room TEXT,
                                    energyrate TEXT,
                                    energyrate_val TEXT,
                                    postcode TEXT,
                                    PRIMARY KEY(address)
                                ) WITHOUT ROWID; """
                curser.execute(sql_create_table)
                curser.executemany(f"INSERT OR REPLACE INTO postcode_info_data_table_{data_index} (inspection_date, address, floor_area, habitable_room, energyrate, energyrate_val, postcode) VALUES (?,?,?,?,?,?,?)", row_total_lst)
            conn.close()
            # add row to saved_postcode_lst 
            saved_postcode_lst.append(cur_postcode_name)
            if len(saved_postcode_lst) > CHUNK_SIZE // 10: # save to file immediately 
                with savedpstcdlock:
                    with open('./running_input/postcode_alr_saved_lst.txt', 'a') as f:
                        for pcl in saved_postcode_lst:
                            f.write(str(pcl)+"\n")
                        saved_postcode_lst[:] = [] # manager list remove all 
            
            # backto search bar
            back_but_ele = sleepy_find_element(driver, [By.XPATH, back_but_xp])
            back_but_ele.click()
            
    except Exception as e:
        logger.error(f"Unsovable Error: {e}")
        if driver is not None:
            driver.close()
            time.sleep(0.2)
            driver.quit()
            time.sleep(0.2)
            driver = None 
            
    finally:
        with chromelock:
            chrome_profile_path_lst.append(chrome_profile_path) # return profile path to list
        time.sleep(3)
        if driver is not None:
            driver.close()
            time.sleep(2)
            driver.quit()
            time.sleep(2)
            driver = None 
            
        if len(saved_postcode_lst) > 0: 
            with savedpstcdlock:
                with open('./running_input/postcode_alr_saved_lst.txt', 'a') as f:
                    for pcl in saved_postcode_lst:
                        f.write(str(pcl)+"\n")
                    saved_postcode_lst[:] = [] # manager list remove all 
                    
        if len(no_data_lst) > 0:  
            logger.info(f"No Data list {no_data_lst}")
            with nodatalock:
                with open('./running_input/postcode_no_data_lst.txt', 'a') as f:
                    for pcl in no_data_lst:
                        f.write(str(pcl)+"\n")
                    no_data_lst[:] = [] # manager list remove all 
        

# %%
def helperf(args):
    return collect_data_multiprocessing(*args)


if __name__ == '__main__':
    if os.name == "nt":
        mp.set_start_method('spawn', force=True)
    else:
        mp.set_start_method('fork', force=True)
        
    manager = Manager() # Manager dictionary must be used for multiprocessing
    # m_saved_postcode_lst = manager.list(saved_postcode_lst)
    # m_no_data_lst = manager.list(no_data_lst)
    m_chromelock = manager.Lock()
    m_nodatalock = manager.Lock()
    m_savedpstcdlock = manager.Lock()
    m_loggingqueue = manager.Queue()

    parser = argparse.ArgumentParser()
    parser.add_argument('--data_index', type=int, required=True, choices=[1,2,3])
    args = parser.parse_args()
    data_index = args.data_index
    
    # make chrome profile 
    for i in range(PROCESS_NUM):
        chrome_profile_path = f"./chrome_profile/chrome_profile_propertydata_co_uk_{i+1}"
        if not os.path.exists(chrome_profile_path):
            Path(chrome_profile_path).mkdir(parents=True, exist_ok=True)
                
    # setup logger 
    loggername = "web_scraping_status_logger"
    loggingfile = "web_scraping_status.log"
    logger = setupLogger(loggername, loggingfile, loggingqueue=m_loggingqueue)
        
    if os.path.exists('./running_input/postcode_no_data_lst.txt'):
        with open('./running_input/postcode_no_data_lst.txt', 'r') as f:
            no_data_lst = f.read()
            no_data_lst = no_data_lst.split('\n')
    else:
        no_data_lst = []
    logger.info(f"No Data list len {len(no_data_lst)}")

    # make running_output dir 
    Path('./running_output').mkdir(parents=True, exist_ok=True)

    # %%
    # get postcode list from local 
    with open(f"./running_input/postcode_list_sub_{data_index}.pkl", 'rb') as f:
        postcode_list = pickle.load(f)
    logger.info(f'Postcode_list len raw: {len(postcode_list)}')    
    if os.path.exists('./running_input/postcode_alr_saved_lst.txt'):
        with open('./running_input/postcode_alr_saved_lst.txt', 'r') as f:
            alr_saved_pstcd_list = f.read()
            alr_saved_pstcd_list = alr_saved_pstcd_list.split('\n')
        # to dict
        alr_saved_pstcd_dct = {x:None for x in alr_saved_pstcd_list}
        no_data_dict = {x:None for x in no_data_lst}
        postcode_list_temp = []
        for pc in tqdm(postcode_list):
            if pc not in alr_saved_pstcd_dct and pc not in no_data_dict:
                postcode_list_temp.append(pc)
        postcode_list = postcode_list_temp
    logger.info(f'Postcode_list len after filtering: {len(postcode_list)}')
    


    # %%
    saved_postcode_lst = []
    profile_path_list = glob(os.path.join(os.path.abspath(os.getcwd()), "chrome_profile", "chrome_profile_propertydata_co_uk_*"))

    m_profile_path_list = manager.list(profile_path_list)
    

    
    # %%
    postcode_list_chunks = [postcode_list[x:x+CHUNK_SIZE] for x in range(0, len(postcode_list), CHUNK_SIZE)]
    
    # %%
    args = [(chunk, m_chromelock,m_nodatalock,m_savedpstcdlock,m_loggingqueue, m_profile_path_list, loggername, loggingfile, data_index) for chunk in postcode_list_chunks]
    
    try:
        with mp.Pool(PROCESS_NUM) as pool:
            results = list(logging_tqdm(pool.imap(helperf, args, chunksize=1), total=len(args),
                                        loggername=loggername,
                                        loggingfile=loggingfile,
                                        loggingqueue=m_loggingqueue,
                                        desc="Progress Status in Main Process"))

    except Exception as e:
        logger.error(e)
        raise e
    finally:
        active_children = mp.active_children()
        for p in active_children:
            p.kill()
            p.join()
        logger.info("Killing all processes")