-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllRecipesParser.java
More file actions
432 lines (402 loc) · 15.1 KB
/
AllRecipesParser.java
File metadata and controls
432 lines (402 loc) · 15.1 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AllRecipesParser {
private String baseUrl;
private Document currentDoc;
// mapping of all the articles on a website
// key value - article title
// value - article url
private Map<String, String> articleMap;
public AllRecipesParser(String baseUrl) {
this.baseUrl = baseUrl;
try {
this.currentDoc = Jsoup.connect(this.baseUrl).get();
} catch (IOException e) {
this.currentDoc = null;
System.out.println("baseUrl can't connect");
}
this.articleMap = new HashMap<>();
}
public Map<String, String> getArticleMap() {
return this.articleMap;
}
/**
* update currentDoc
*/
public void resetCurrentDoc() {
try {
this.currentDoc = Jsoup.connect(this.baseUrl).get();
} catch (IOException e) {
this.currentDoc = null;
System.out.println("set url can't connect");
}
}
/**
* maps Meal Types Article Titles to the link for them
*
* "Breakfast And Brunch Recipes" (artTitle) to
* the url for this link (artUrl)
* https://www.allrecipes.com/recipes/78/breakfast-and-brunch/
*
* Breakfast And Brunch Recipes
* Lunch Recipes
* Dinner Recipes
* Appetizer & Snack Recipes
* Bread Recipes
* Dessert Recipes
* Drink Recipes
* Main Dishes
* Salad Recipes
* Side Dish Recipes
* Soup, Stew & Chili Recipes
*/
public void makeArtMapMealType() {
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return;
}
Elements artElts = this.currentDoc.select("span");
for (Element art: artElts) {
String idTag = art.attr("id");
boolean isRecipe = art.text().contains("Recipes") || art.text().contains("Dishes");
if (idTag.contains("submenu-label") && isRecipe) {
String artTitle = art.text();
Element parent = art.parent().parent();
Elements elts = parent.select("a");
for (int i = 0; i < elts.size(); i++) {
Element a = elts.get(i);
if (a.text().equals("See All " + artTitle)) {
String artUrl = a.attr("href");
this.articleMap.put(artTitle, artUrl);
}
}
}
}
}
/**
* assumes some ARParser object w/ baseUrl for a meal type,
* like "Breakfast and Brunch Recipes"'s url
* and gets all the subcategories on the carousel
* gets titles and urls associated with that
*/
public void makeArtMapMealFoods() {
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return;
}
Elements artElts = this.currentDoc.select("div");
for (Element art: artElts) {
String classTag = art.attr("class");
if(classTag.equals("carouselNav__linkText elementFont__fine")) {
String artTitle = art.text();
Element parent = art.parent();
String artUrl = parent.attr("href");
this.articleMap.put(artTitle, artUrl);
}
}
}
/**
* assumes some ARParser object w/ baseUrl for a food category,
* like "Pancakes"'s url
* and gets all the Recipe title / urls under this food category
* gets titles and urls associated with that
*/
public void makeArtMapRecipes() {
// limit for num recipes so parsing doesn't take too long
int limit = 10;
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return;
}
Elements artElts = this.currentDoc.select("h3");
for (Element art: artElts) {
//System.out.println(art.text());
String classTag = art.attr("class");
if(classTag.equals("card__title elementFont__resetHeading") && this.articleMap.size() < limit) {
String artTitle = art.text();
Element parent = art.parent();
String artUrl = parent.attr("href");
//System.out.println(artTitle + " " + artUrl);
this.articleMap.put(artTitle, artUrl);
}
}
Elements nextElts = this.currentDoc.select("div");
for (Element art: nextElts) {
//System.out.println(art.text());
String idTag = art.attr("id");
if(idTag.equals("category-page-list-related-load-more-container")) {
//String artTitle = art.text();
String artUrl = art.select("a").get(0).attr("href");
//System.out.println(artUrl);
this.baseUrl = artUrl;
resetCurrentDoc(); // update current doc
visitNextPages(0);
//System.out.println(artTitle + " " + artUrl);
//this.articleMap.put(artTitle, artUrl);
}
}
}
/**
* Assumes we are at a page reached after clicking "Load More"
* and goes to the pages you would
* get after clicking "Next"
*
* Updates articleMap when visiting next pages
*/
public void visitNextPages(int count) {
int limit = 10;
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return;
}
String nextUrl = "";
Elements artElts = this.currentDoc.select("a");
//System.out.println(artElts.size());
for (Element art: artElts) {
//System.out.println(art.text());
String classTag = art.attr("class");
//System.out.println(classTag);
if(classTag.equals("tout__titleLink elementFont__toutLink") && this.articleMap.size() < limit) {
//System.out.println("yea");
String artTitle = art.text();
String artUrl = art.attr("href");
if (!artUrl.contains("https://")) {
artUrl = "https://www.allrecipes.com" + artUrl;
}
//System.out.println(artTitle + " " + artUrl);
this.articleMap.put(artTitle, artUrl);
}
// check if there's a "Next" Button
// if so, store the url to use later
if (art.text().equals("Next")) {
nextUrl = art.attr("href");
//System.out.println(nextUrl);
}
}
// check if need to visit next pages
if (count < 1) {
if (nextUrl.length() > 0) {
//System.out.println("here");
this.baseUrl = nextUrl;
resetCurrentDoc();
visitNextPages(count + 1);
}
}
}
/**
* assumes currentDoc is at a recipe page
* @return an arraylist of String ingredients (empty if current
* doc is null)
*
*/
public String getIngreds() {
String ingreds = "";
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return ingreds;
}
Elements artElts = this.currentDoc.select("span");
for (Element art: artElts) {
String classTag = art.attr("class");
if(classTag.equals("ingredients-item-name elementFont__body")) {
String artTitle = art.text();
ingreds += artTitle + " ; "; // Added semi colon here! For gui to look right - claire
}
}
return ingreds;
}
/**
* assumes currentDoc is at a recipe page
* @return an arraylist of String directions (empty if current
* doc is null)
*
*/
public ArrayList<String> getDirections() {
ArrayList<String> steps = new ArrayList<>();
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return steps;
}
Elements artElts = this.currentDoc.select("div");
for (Element art: artElts) {
String classTag = art.attr("class");
if(classTag.equals("section-body elementFont__body--paragraphWithin elementFont__body--linkWithin")) {
String artTitle = art.text();
steps.add(artTitle);
}
}
return steps;
}
/**
* assumes currentDoc is at a recipe page
* @return an arraylist of String directions (empty if current
* doc is null)
*
*/
public String getImageUrl(String recTitle) {
String imgUrl = "";
if (this.currentDoc == null) {
System.out.println("Current doc is null");
return imgUrl;
}
Elements artElts = this.currentDoc.select("div");
for (Element art: artElts) {
String classTag = art.attr("class");
//System.out.println(classTag);
Elements children = art.children();
if(classTag.equals("image-container")) {
//System.out.println("art text: " + art.text());
for (Element child: children) {
String dataSrcTag = child.attr("data-src");
//System.out.println("data-alt: " + dataSrcTag);
imgUrl = dataSrcTag;
if (imgUrl.length() > 0) {
return imgUrl;
}
}
}
if (classTag.contains("component lazy-image lazy-image-udf")) {
if (art.text().contains(recTitle)) {
imgUrl = art.attr("data-src");
if (imgUrl.length() > 0) {
return imgUrl;
}
}
}
}
return imgUrl;
}
/**
* star rating
* Assumes connection with a recipe Document
* Modifies recipeData
*/
public void populateStarRating(Map<String, String[]> recipeData, String recipeName, int index, int length) {
double sum = 0;
int starCount = 5;
int count = 0;
Elements artElts = this.currentDoc.select("li");
for (Element art: artElts) {
String classTag = art.attr("class");
//System.out.println(classTag); recipeNutritionSectionBlock
Elements children = art.children();
if (classTag.equals("rating") && starCount > 0) {
if (art.text().contains("star values: ")) {
int startIndex = art.text().indexOf("star values: ") + "star values: ".length();
String value = art.text().substring(startIndex);
try {
int numValue = Integer.parseInt(value);
count += numValue;
sum += numValue * starCount;
//System.out.println("num " + numValue + " count " + count + " sum " + sum);
starCount--;
} catch (NumberFormatException e) {
// do nothing
}
}
}
}
double avg = 0;
if (count > 0) {
avg = sum / count;
avg = Math.round(avg * 100.0) / 100.0;
}
if (!recipeData.containsKey(recipeName)) {
recipeData.put(recipeName, new String[length]);
}
recipeData.get(recipeName)[index] = "" + avg;
}
/**
* cooking time
* Assumes connection with a recipe Document
* Modifies recipeData
*/
public void populateCookingTime(Map<String, String[]> recipeData, String recipeName, int index, int length) {
Elements artElts = this.currentDoc.select("div");
for (Element art: artElts) {
String classTag = art.attr("class");
//System.out.println(classTag); recipeNutritionSectionBlock
Elements children = art.children();
if (classTag.equals("recipe-meta-item")) {
String timeInfo = art.text();
String totalTime = "";
if (timeInfo.contains("total: ")) {
int startIndex = timeInfo.indexOf("total: ") + "total: ".length();
totalTime = timeInfo.substring(startIndex);
//System.out.println(totalTime);
if (!recipeData.containsKey(recipeName)) {
recipeData.put(recipeName, new String[length]);
}
recipeData.get(recipeName)[index] = "" + timeHelper(totalTime);
return;
}
}
}
if (recipeData.get(recipeName)[index] == null) {
recipeData.get(recipeName)[index] = "60"; // default value of 60 mins
}
}
/**
* takes in a String of words representing time amount
* and returns the number version
* (example: 1 hr 15 mins --> 75)
* @param timeWords
* @return
*/
public int timeHelper(String timeWords) {
int time = 0;
String[] timeArray = timeWords.split(" ");
for (int i = 0; i < timeArray.length - 1; i++) {
try {
int duration = Integer.parseInt(timeArray[i]);
if (timeArray[i + 1].equals("hr")) {
time += duration * 60;
} else if (timeArray[i + 1].equals("mins")) {
time += duration;
}
} catch (NumberFormatException e) {
// do nothing
}
}
return time;
}
/**
* calorie info
* Assumes connection with a recipe Document
* Modifies recipeData
*/
public void populateCalorieInfo(Map<String, String[]> recipeData, String recipeName, int index, int length) {
Elements artElts = this.currentDoc.select("div");
for (Element art: artElts) {
String classTag = art.attr("class");
//System.out.println(classTag); recipeNutritionSectionBlock
Elements children = art.children();
if(classTag.equals("recipeNutritionSectionBlock")) {
//System.out.println("art text: " + art.text());
for (Element child: children) {
String nutrInfo = child.text();
String calCount = "";
if (nutrInfo.contains("calories")) {
int endIndex = nutrInfo.indexOf("calories");
calCount = nutrInfo.substring(0, endIndex);
if (!recipeData.containsKey(recipeName)) {
recipeData.put(recipeName, new String[length]);
}
recipeData.get(recipeName)[index] = calCount;
return;
}
}
}
}
if (recipeData.get(recipeName)[index] == null) {
recipeData.get(recipeName)[index] = "500 "; // default value of 500 calories
}
}
}