-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
114 lines (90 loc) · 3.5 KB
/
main.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
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
import frontmatter
import re
import requests
import sys
import typer
from bs4 import BeautifulSoup
from pathlib import Path
from slugify import slugify
URL = "https://www.downtownlawrence.com/explore-downtown-lawrence/dining/"
app = typer.Typer()
@app.command()
def sync_downtownlawrence(mark_inactive: bool = False, use_cache: bool = False):
if not Path("_places").exists():
Path("_places").mkdir()
if mark_inactive:
filenames = Path("_places").glob("*.md")
for filename in filenames:
post = frontmatter.loads(filename.read_text())
post["active"] = False
filename.write_text(frontmatter.dumps(post))
if use_cache:
cache_filename = f"{slugify(URL)}.html"
if Path(cache_filename).exists():
text = Path(cache_filename).read_text()
else:
response = requests.get(URL)
response.raise_for_status()
text = response.text
text = Path(cache_filename).write_text(text)
else:
response = requests.get(URL)
response.raise_for_status()
text = response.text
soup = BeautifulSoup(text, "html.parser")
table = soup.find("div", "entry-content")
rows = table.find_all("p")
typer.secho(f"Businesses found: {len(rows)}", fg="yellow")
for row in rows[3:]:
if len(row.text.strip()):
try:
tokens = row.find_all(recursive=False)
# print(tokens)
# print(row.text.replace("\xa0", "\n").split("\n"))
name = tokens[0]
name = name.text.strip()
# name, address, services = row.find_all("td")
place_slug = slugify(name)
typer.secho(f"{name} [{place_slug}]", fg="green")
try:
facebook_url = [
item.get("href")
for item in row.find_all(href=re.compile("facebook"))
][0]
print(facebook_url)
except IndexError:
facebook_url = ""
url = row.find("a")
url = url.get("href") if url else ""
if url:
if url.startswith("http"):
if url.startswith("http://"):
url = url.replace("http://", "https://")
else:
url = f"https://{url}"
if "facebook.com" in url:
url = ""
typer.echo(url)
filename = Path("_places").joinpath(f"{place_slug}.md")
if filename.exists():
post = frontmatter.loads(filename.read_text())
else:
post = frontmatter.loads("")
post["active"] = False if "Closed" in row.text else True
# post["address"] = address.text
post["name"] = name
post["facebook_url"] = facebook_url
post["neighborhood"] = "Downtown"
# post["notes"] = services.text
post["sitemap"] = False
post["slug"] = place_slug
post["url"] = url
Path("_places").joinpath(f"{place_slug}.md").write_text(
frontmatter.dumps(post)
)
print("")
except (IndexError, ValueError) as e:
typer.secho(e, fg="red")
print(row)
if __name__ == "__main__":
app()