Created
December 12, 2021 19:11
-
-
Save turtlemonvh/dcacc6026a3bb9a5abd3b20eeaf1fac0 to your computer and use it in GitHub Desktop.
Parse Minted Contacts Print View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
import sys | |
from bs4 import BeautifulSoup as bs | |
""" | |
Minted allows you to import CSV/XLSX, etc, but doesn't provide an easy export. This helps with that. | |
The script parses contacts "exported" via Minted's print function into a CSV. | |
Not my best work, but it should save some time if anybody else needs to do this again. | |
Call like this, where "contacts-2021-12-12.html" is the html contents of the page presented for printing contacts (see: https://help2.minted.com/s/article/print-my-contact-list) | |
python parse_print_contacts_html.py < contacts-2021-12-12.html > contacts-2021-12-12.csv | |
""" | |
soup = bs(sys.stdin, 'html.parser') | |
contacts = soup.body.find_all('li') | |
fieldnames = ['name', 'address_1', 'address_2', 'city', 'state', 'zip'] | |
writer = csv.DictWriter(sys.stdout, fieldnames=fieldnames) | |
writer.writeheader() | |
for contact in contacts: | |
name = contact.select(".contact-name")[0].string.strip() | |
address_str = contact.select(".contact-address")[0].get_text().strip() | |
address_parts = address_str.split("\n") | |
if address_str == '': | |
# Empty | |
address_1 = '' | |
address_2 = '' | |
address_3 = '' | |
elif len(address_parts) < 2: | |
# 1 non-empty | |
address_1 = address_parts[0].strip() | |
address_2 = '' | |
address_3 = '' | |
elif len(address_parts) < 3: | |
# 2 non-empty; 2nd part is city, state, zip | |
address_1 = address_parts[0].strip() | |
address_2 = address_parts[1].strip() | |
address_3 = address_2 | |
address_2 = '' | |
else: | |
# 3 non-empty | |
address_1 = address_parts[0].strip() | |
address_2 = address_parts[1].strip() | |
address_3 = address_parts[2].strip() | |
if address_3: | |
address_3_parts = address_3.split(",") | |
city = address_3_parts[0].strip() | |
state_zip = address_3_parts[1].strip() | |
zip_code = state_zip.split(" ")[-1] | |
state = " ".join(state_zip.split(" ")[0:-1]) | |
else: | |
city = '' | |
zip_code = '' | |
state = '' | |
writer.writerow({ | |
'name': name, | |
'address_1': address_1, | |
'address_2': address_2, | |
'city': city, | |
'state': state, | |
'zip': zip_code | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment