forked from hhursev/recipe-scrapers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathallrecipes.py
182 lines (143 loc) · 5.78 KB
/
allrecipes.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# mypy: disallow_untyped_defs=False
from ._abstract import AbstractScraper
from ._utils import get_minutes, get_yields, normalize_string
class AllRecipes:
@classmethod
def host(cls):
return "allrecipes.com"
def __new__(cls, url, *args, **kwargs):
if AllRecipesUser.host() in url:
return AllRecipesUser(url, *args, **kwargs)
return AllRecipesCurated(url, *args, **kwargs)
class AllRecipesCurated(AbstractScraper):
@classmethod
def host(cls):
return "allrecipes.com"
def author(self):
# NB: In the schema.org 'Recipe' type, the 'author' property is a
# single-value type, not an ItemList.
# allrecipes.com seems to render the author property as a list
# containing a single item under some circumstances.
# In those cases, the SchemaOrg class will fail due to the unexpected
# type, and this method is called as a fallback.
# Rather than implement non-standard handling in SchemaOrg, this code
# provides a (hopefully temporary!) allrecipes-specific workaround.
author = self.schema.data.get("author")
if author and isinstance(author, list) and len(author) == 1:
author = author[0].get("name")
return author
def title(self):
return self.schema.title()
def description(self):
return self.schema.description()
def cook_time(self):
return self.schema.cook_time()
def prep_time(self):
return self.schema.prep_time()
def total_time(self):
return self.schema.total_time()
def yields(self):
return self.schema.yields()
def image(self):
return self.schema.image()
def ingredients(self):
return self.schema.ingredients()
def instructions(self):
return self.schema.instructions()
def ratings(self):
return self.schema.ratings()
def cuisine(self):
return self.schema.cuisine()
def category(self):
return self.schema.category()
class AllRecipesUser(AbstractScraper):
"""Parse "unpublished" personal recipes on AllRecipes.com.
Unpublised recipes are not structured, unlike curated recipes.
Certain information is not always available, as it relies on what the
users provided.
"""
@classmethod
def host(cls):
return "allrecipes.com/cook"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# meta contains servings and yields, as well as preparation, cooking,
# and total times
# Possible keys are 'servings', 'yield', 'cook', 'prep', 'total'
meta = zip(
self.soup.findAll("div", {"class": "recipe-meta-item-header"}),
self.soup.findAll("div", {"class": "recipe-meta-item-body"}),
)
self.meta = {
k.text.lower().rstrip(":"): normalize_string(v.text) for k, v in meta
}
def title(self):
title = self.soup.find("h1", {"class": "heading-content"}).text
return title
def total_time(self):
if "total" in self.meta:
total_time = get_minutes(self.meta["total"], return_zero_on_not_found=True)
else:
total_time = get_minutes(self.meta.get("cook", 0)) + get_minutes(
self.meta.get("prep", 0)
)
return total_time
def yields(self):
yield_data = self.meta.get("yield")
if yield_data is None:
yield_data = self.meta.get("servings")
return get_yields(yield_data)
def image(self):
image = self.soup.find("div", {"class": "lead-media", "data-src": True})
image = image.get("data-src")
return image
def nutrients(self):
raise NotImplementedError("Not available for personal recipes.")
def ingredients(self):
ingredients = self.soup.findAll("span", {"class": "ingredients-item-name"})
ingredients = [normalize_string(i.text) for i in ingredients]
return ingredients
def instructions(self):
instructions = self.soup.findAll("div", {"class": "paragraph"})
instructions = "\n".join(normalize_string(i.text) for i in instructions)
return instructions
def ratings(self):
lacks_rating = self.soup.find("a", {"class": "no-ratings"})
if lacks_rating:
return None
ratings = self.soup.find("span", {"class": "review-star-text"})
return float(ratings.text.lstrip("Ratings:").rstrip("stars"))
def author(self):
author = self.soup.find("span", {"class": "author-name"}).text
return author
def reviews(self):
"""Return a list of dictionaries containing reviews.
Each dictionary contains the author, datePublished, reviewRating, reviewBody.
These keys follow the JSON-LD format.
"""
reviews = []
for element in zip(
self.soup.findAll("span", {"class": "reviewer__name"}), # name
self.soup.findAll("span", {"class": "feedback__reviewDate"}), # date
self.soup.findAll("span", {"class": "review-star-text"}), # rating
self.soup.findAll("div", {"class": "feedback__reviewBody"}), # comment
):
name, date, rating, comment = element
name = normalize_string(name.text)
date = date.text
# The value is "Ratings: 4 stars"
rating = float(rating.text.lstrip("Ratings:").rstrip("stars"))
comment = normalize_string(comment.text)
reviews.append(
{
"author": name,
"datePublished": date,
"reviewRating": rating,
"reviewBody": comment,
}
)
return reviews
def cuisine(self):
return None
def category(self):
return None