File size: 4,703 Bytes
fa18ce9 1c69cf4 fa18ce9 1c69cf4 fa18ce9 2454a5f fa18ce9 2454a5f fa18ce9 |
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 |
import requests
from bs4 import BeautifulSoup
import glob
import json
def download_recipes():
next_category_page = "https://en.wikibooks.org/wiki/Category:Recipes"
page_number = 0
while next_category_page is not None:
r = requests.get(next_category_page)
next_category_page = None
soup = BeautifulSoup(r.text, features="html.parser")
mw_pages = soup.select("#mw-pages")[0]
recipe_number = 0
for a in mw_pages.find_all("a"):
if a["href"].endswith("#mw-pages") and a.text == "next page":
print(a["href"])
next_category_page = f"https://en.wikibooks.org{a['href']}"
elif a["href"].startswith("/wiki/Cookbook:"):
r2 = requests.get(f"https://en.wikibooks.org{a['href']}")
if r2.status_code == 200:
print("\tdownloading:", a["href"])
with open(f"recipes/recipe_{page_number:02}_{recipe_number:03}.html", "w") as f:
f.write(r2.text)
else:
print("WARNING: could not download:", a["href"])
recipe_number += 1
page_number += 1
def parse_recipes():
recipes = []
for recipe_file in sorted(glob.glob("recipes/*.html")):
print("parsing: ", recipe_file)
recipe_data = parse_recipe(recipe_file)
recipes.append({"filename": recipe_file, "recipe_data": recipe_data})
with open("recipes_parsed.json", "w") as f:
json.dump(recipes, f, ensure_ascii=False, indent=4)
with open("recipes_parsed.mini.json", "w") as f:
json.dump(recipes, f, ensure_ascii=True)
def parse_recipe(filename):
with open(filename) as f:
soup = BeautifulSoup(f.read(), features="html.parser")
recipe_title = soup.select("#firstHeading")[0].get_text().replace("Cookbook:", "")
recipe_url = soup.find("link", attrs={"rel": "canonical"})["href"]
infoboxes = soup.select("table.infobox")
if len(infoboxes) >= 1:
recipe_info = parse_infobox(infoboxes[0])
else:
print(f"[{filename}] WARNING: no infobox found")
recipe_info = None
content = soup.select("div.mw-content-ltr")[0]
section_name = None
text_lines = []
for i, child in enumerate(content):
if child.name == "p" and child.get_text().startswith("Cookbook | Recipes | Ingredients |"):
continue # skip the first p (navigation bar)
elif child.name == "div" and " ".join(child.get("class", [])) == "mw-heading mw-heading2":
section_name = child.find("h2").text
elif child.name in ["p", "blockquote"]:
text_lines.append({
"text": child.get_text().strip(),
"line_type": child.name,
"section": section_name
})
elif child.name in ["ul", "ol"]:
for li in child.find_all("li"):
text_lines.append({
"text": li.get_text().strip(),
"line_type": child.name,
"section": section_name
})
return {
"url": recipe_url,
"title": recipe_title,
"infobox": recipe_info,
"text_lines": text_lines
}
def parse_infobox(infobox):
recipe_info = {
"category": None,
"servings": None,
"time": None,
"difficulty": None
}
for tr in infobox.select("tr"):
if not tr.select("th"):
continue
if tr.find("th").text == "Category":
category_link = tr.find("td").find("a")
if category_link:
recipe_info["category"] = category_link["href"]
elif tr.find("th").text == "Servings":
recipe_info["servings"] = tr.find("td").text
elif tr.find("th").text == "Time":
recipe_info["time"] = tr.find("td").text
elif tr.find("th").text == "Difficulty":
difficulty_link = tr.select("a.mw-file-description")
if difficulty_link:
recipe_info["difficulty"] = parse_difficulty(difficulty_link[0]["href"])
return recipe_info
def parse_difficulty(svg_filename):
if svg_filename == "/wiki/File:1o5dots.svg":
return 1
elif svg_filename == "/wiki/File:2o5dots.svg":
return 2
elif svg_filename == "/wiki/File:3o5dots.svg":
return 3
elif svg_filename == "/wiki/File:4o5dots.svg":
return 4
elif svg_filename == "/wiki/File:5o5dots.svg":
return 5
else:
raise ValueError("Invalid difficulty level filename")
if __name__ == "__main__":
# download_recipes()
parse_recipes() |