-
Notifications
You must be signed in to change notification settings - Fork 2
/
arrl-call-sign-search.py
executable file
·89 lines (73 loc) · 2.67 KB
/
arrl-call-sign-search.py
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
#!/usr/bin/env python3
import argparse
import lxml.html
import re
import requests
import sys
import tabulate
def build_query_payload(callsign: str) -> dict:
query_payload = {}
query_payload["_method"] = "POST"
query_payload["data[Search][terms]"] = callsign
return query_payload
if __name__ == "__main__":
# set up command arguments
parser = argparse.ArgumentParser(
description="Ham Radio Call Sign Search Utility - ARRL"
)
parser.add_argument(
"--pretty", required=False, action="store_true", help="print pretty format"
)
parser.add_argument("callsign", type=str, help="ham radio call sign string")
args = parser.parse_args()
# set up constants
arrl_call_sign_search_url = "https://www.arrl.org/advanced-call-sign-search"
output = {}
# build query payload
payload = build_query_payload(args.callsign)
# send HTTP request and process the response
try:
response = requests.post(arrl_call_sign_search_url, data=payload)
except Exception as e:
print(f"ERROR: Could not send HTTP request to ARRL URL: {e}", file=sys.stderr)
sys.exit(2)
if response.status_code != 200:
print(
"ERROR: Non-200 HTTP response code retrieved from ARRL URL", file=sys.stderr
)
sys.exit(3)
response_xml = lxml.html.fromstring(response.text)
try:
title = response_xml.xpath("//div[@class='list2']/ul/li/h3/text()")[0]
call_sign_details_response = response_xml.xpath(
"//div[@class='list2']/ul/li/p/text()"
)
# some results do not have <p> tag
if not call_sign_details_response:
call_sign_details_response = response_xml.xpath(
"//div[@class='list2']/ul/li/text()"
)
except Exception:
print(f"ERROR: Could not get proper response from ARRL URL", file=sys.stderr)
sys.exit(4)
# generate output
output["title"] = re.sub(r"\t+", "", title.strip())
output["basic_info"] = []
output["tables"] = []
for item in call_sign_details_response:
if not re.match(r"^\s+$", item):
line = re.sub(r"\t+", "", item).strip()
if re.match(r".*:\s+.*", line):
key, value = line.split(":")
output["tables"].append([key, value.strip()])
else:
output["basic_info"].append(line)
print(output["title"])
for item in output["basic_info"]:
print(item)
if args.pretty:
table_format = "simple_grid"
print(tabulate.tabulate(output["tables"], tablefmt=table_format))
else:
for item in output["tables"]:
print(f"{item[0]}: {item[1]}")