|
""" |
|
Cannabis Licenses | Get New Mexico Licenses |
|
Copyright (c) 2022 Cannlytics |
|
|
|
Authors: |
|
Keegan Skeate <https://github.com/keeganskeate> |
|
Candace O'Sullivan-Sutherland <https://github.com/candy-o> |
|
Created: 9/29/2022 |
|
Updated: 10/6/2022 |
|
License: <https://github.com/cannlytics/cannlytics/blob/main/LICENSE> |
|
|
|
Description: |
|
|
|
Collect New Mexico cannabis license data. |
|
|
|
Data Source: |
|
|
|
- New Mexico Regulation and Licensing Department | Cannabis Control Division |
|
URL: <https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US> |
|
|
|
""" |
|
|
|
from datetime import datetime |
|
import os |
|
from time import sleep |
|
from typing import Optional |
|
|
|
|
|
from cannlytics.data.gis import geocode_addresses, search_for_address |
|
from dotenv import dotenv_values |
|
import pandas as pd |
|
|
|
|
|
from selenium import webdriver |
|
from selenium.webdriver.chrome.options import Options |
|
from selenium.webdriver.common.by import By |
|
from selenium.webdriver.chrome.service import Service |
|
from selenium.webdriver.support import expected_conditions as EC |
|
from selenium.webdriver.support.ui import WebDriverWait |
|
try: |
|
import chromedriver_binary |
|
except ImportError: |
|
pass |
|
|
|
|
|
|
|
DATA_DIR = '../data/nm' |
|
ENV_FILE = '../.env' |
|
|
|
|
|
STATE = 'NM' |
|
NEW_MEXICO = { |
|
'licensing_authority_id': 'NMCCD', |
|
'licensing_authority': 'New Mexico Cannabis Control Division', |
|
'licenses_url': 'https://nmrldlpi.force.com/bcd/s/public-search-license?division=CCD&language=en_US', |
|
} |
|
|
|
|
|
def get_licenses_nm( |
|
data_dir: Optional[str] = None, |
|
env_file: Optional[str] = '.env', |
|
): |
|
"""Get New Mexico cannabis license data.""" |
|
|
|
|
|
if not os.path.exists(data_dir): os.makedirs(data_dir) |
|
|
|
|
|
service = Service() |
|
options = Options() |
|
options.add_argument('--window-size=1920,1200') |
|
|
|
|
|
options.headless = False |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
driver = webdriver.Chrome(options=options, service=service) |
|
|
|
|
|
driver.get(NEW_MEXICO['licenses_url']) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sleep(5) |
|
|
|
|
|
content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea') |
|
radio = content.find_element(by=By.CLASS_NAME, value='slds-radio--faux') |
|
radio.click() |
|
sleep(2) |
|
|
|
|
|
|
|
|
|
search = content.find_element(by=By.ID, value='comboboxId-40') |
|
search.click() |
|
choices = content.find_elements(by=By.CLASS_NAME, value='slds-listbox__item') |
|
for choice in choices: |
|
if choice.text == 'Cannabis Retailer': |
|
choice.click() |
|
sleep(2) |
|
break |
|
|
|
|
|
search = content.find_element(by=By.CLASS_NAME, value='vlocity-btn') |
|
search.click() |
|
sleep(2) |
|
|
|
|
|
|
|
sleep(5) |
|
data = [] |
|
iterate = True |
|
while(iterate): |
|
|
|
|
|
items = content.find_elements(by=By.CLASS_NAME, value='block-container') |
|
for item in items[3:]: |
|
text = item.text |
|
if not text: |
|
continue |
|
values = text.split('\n') |
|
data.append({ |
|
'license_type': values[0], |
|
'license_status': values[1], |
|
'business_legal_name': values[2], |
|
'address': values[-1], |
|
'details_url': '', |
|
}) |
|
|
|
|
|
|
|
par = content.find_elements(by=By.TAG_NAME, value='p')[-1].text |
|
page_number = int(par.split(' ')[2]) |
|
total_pages = int(par.split(' ')[-2]) |
|
if page_number == total_pages: |
|
iterate = False |
|
|
|
|
|
buttons = content.find_elements(by=By.TAG_NAME, value='button') |
|
for button in buttons: |
|
if button.text == 'Next Page': |
|
button.click() |
|
sleep(5) |
|
break |
|
|
|
|
|
retailers = pd.DataFrame(columns=['business_legal_name']) |
|
for i, licensee in enumerate(data): |
|
|
|
|
|
if len(retailers.loc[retailers['business_legal_name'] == licensee['business_legal_name']]): |
|
continue |
|
|
|
|
|
content = driver.find_element(by=By.CLASS_NAME, value='siteforceContentArea') |
|
radio = content.find_elements(by=By.CLASS_NAME, value='slds-radio--faux')[1] |
|
radio.click() |
|
sleep(1) |
|
|
|
|
|
search_field = content.find_element(by=By.CLASS_NAME, value='vlocity-input') |
|
search_field.clear() |
|
search_field.send_keys(licensee['business_legal_name']) |
|
|
|
|
|
search = content.find_element(by=By.CLASS_NAME, value='vlocity-btn') |
|
search.click() |
|
|
|
|
|
|
|
sleep(1.5) |
|
|
|
|
|
|
|
action = content.find_element(by=By.CLASS_NAME, value='slds-button_icon') |
|
try: |
|
action.click() |
|
except: |
|
continue |
|
|
|
|
|
el = (By.CLASS_NAME, 'body') |
|
WebDriverWait(driver, 5).until(EC.presence_of_element_located(el)) |
|
|
|
|
|
page = driver.find_element(by=By.CLASS_NAME, value='body') |
|
|
|
|
|
|
|
|
|
sleep(1.5) |
|
|
|
|
|
fields = [ |
|
'license_number', |
|
'license_status', |
|
'issue_date', |
|
'expiration_date', |
|
'business_owner_name', |
|
] |
|
values = page.find_elements(by=By.CLASS_NAME, value='field-value') |
|
if len(values) > 5: |
|
for j, value in enumerate(values[:5]): |
|
data[i][fields[j]] = value.text |
|
for value in values[5:]: |
|
data[i]['business_owner_name'] += f', {value.text}' |
|
else: |
|
for j, value in enumerate(values): |
|
data[i][fields[j]] = value.text |
|
|
|
|
|
premises = page.find_elements(by=By.CLASS_NAME, value='block-header') |
|
for premise in premises: |
|
values = premise.text.split('\n') |
|
licensee['address'] = values[0].replace(',', ', ') |
|
licensee['license_number'] = values[2] |
|
retailers = pd.concat([retailers, pd.DataFrame([licensee])]) |
|
|
|
|
|
back_button = page.find_element(by=By.CLASS_NAME, value='vlocity-btn') |
|
back_button.click() |
|
sleep(1) |
|
|
|
|
|
service.stop() |
|
|
|
|
|
retailers = retailers.loc[retailers['license_status'] == 'Active'] |
|
retailers = retailers.assign( |
|
business_email=None, |
|
business_structure=None, |
|
licensing_authority_id=NEW_MEXICO['licensing_authority_id'], |
|
licensing_authority=NEW_MEXICO['licensing_authority'], |
|
license_designation='Adult-Use', |
|
license_status_date=None, |
|
license_term=None, |
|
premise_state=STATE, |
|
parcel_number=None, |
|
activity=None, |
|
business_image_url=None, |
|
business_website=None, |
|
business_phone=None, |
|
id=retailers['license_number'], |
|
business_dba_name=retailers['business_legal_name'], |
|
) |
|
|
|
|
|
retailers['data_refreshed_date'] = datetime.now().isoformat() |
|
|
|
|
|
|
|
config = dotenv_values(env_file) |
|
api_key = config['GOOGLE_MAPS_API_KEY'] |
|
retailers = geocode_addresses(retailers, api_key=api_key, address_field='address') |
|
retailers['premise_street_address'] = retailers['formatted_address'].apply( |
|
lambda x: x.split(',')[0] if STATE in str(x) else x |
|
) |
|
retailers['premise_city'] = retailers['formatted_address'].apply( |
|
lambda x: x.split(', ')[1].split(',')[0] if STATE in str(x) else x |
|
) |
|
retailers['premise_zip_code'] = retailers['formatted_address'].apply( |
|
lambda x: x.split(', ')[2].split(',')[0].split(' ')[-1] if STATE in str(x) else x |
|
) |
|
drop_cols = ['state', 'state_name', 'address', 'formatted_address', |
|
'details_url'] |
|
gis_cols = { |
|
'county': 'premise_county', |
|
'latitude': 'premise_latitude', |
|
'longitude': 'premise_longitude' |
|
} |
|
retailers.drop(columns=drop_cols, inplace=True) |
|
retailers.rename(columns=gis_cols, inplace=True) |
|
|
|
|
|
if data_dir is not None: |
|
if not os.path.exists(data_dir): os.makedirs(data_dir) |
|
timestamp = datetime.now().isoformat()[:19].replace(':', '-') |
|
retailers.to_csv(f'{data_dir}/retailers-{STATE.lower()}-{timestamp}.csv', index=False) |
|
return retailers |
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
import argparse |
|
try: |
|
arg_parser = argparse.ArgumentParser() |
|
arg_parser.add_argument('--d', dest='data_dir', type=str) |
|
arg_parser.add_argument('--data_dir', dest='data_dir', type=str) |
|
arg_parser.add_argument('--env', dest='env_file', type=str) |
|
args = arg_parser.parse_args() |
|
except SystemExit: |
|
args = {'d': DATA_DIR, 'env_file': ENV_FILE} |
|
|
|
|
|
data_dir = args.get('d', args.get('data_dir')) |
|
env_file = args.get('env_file') |
|
data = get_licenses_nm(data_dir, env_file=env_file) |
|
|