forked from iron-bun/python_scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrape_your_plate.py
executable file
·181 lines (144 loc) · 5.92 KB
/
scrape_your_plate.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
#!/usr/bin/env python3
#
# Scrape recipes from pepperplate.com.
#
import requests
from bs4 import BeautifulSoup
import json
import time
import getpass
import re
import os
def pp_login(username, password):
if not password:
password = getpass.getpass('Please enter the password for account {}: '.format(username))
print('Logging into pepperplate.com')
url = 'https://www.pepperplate.com/login.aspx'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"}
s = requests.Session()
s.headers.update(headers)
r = s.get(url)
soup = BeautifulSoup(r.content)
VIEWSTATE = soup.find(id='__VIEWSTATE')['value']
EVENTVALIDATION = soup.find(id='__EVENTVALIDATION')['value']
login_data={"__VIEWSTATE":VIEWSTATE,
"__EVENTVALIDATION":EVENTVALIDATION,
"__EVENTARGUMENT":'',
"__EVENTTARGET":'ctl00$cphMain$loginForm$ibSubmit',
"ctl00$cphMain$loginForm$tbEmail":username,
"ctl00$cphMain$loginForm$tbPassword":password,
"ctl00$cphMain$loginForm$cbRememberMe":'on'
}
r = s.post(url, data=login_data)
if r.url == 'http://www.pepperplate.com/recipes/default.aspx':
print('Login sucessful')
else:
print('Login failed. Please try again')
exit(1)
return s
def pp_get_page(session, page):
print('Downloading page {} of recipes'.format(page+1))
url = 'http://www.pepperplate.com/recipes/default.aspx/GetPageOfResults'
parameters = json.dumps({'pageIndex':page,
'pageSize':20,
'sort':4,
'tagIds': [],
'favoritesOnly':0})
headers={'Referer':'http://www.pepperplate.com/recipes/default.aspx'
,'Content-Type': 'application/json'
,'X-Requested-With': 'XMLHttpRequest'
,'DNT':1
,'Accept': 'application/json, text/javascript, */*; q=0.01'
,'Accept-Language': 'en,de;q=0.7,en-US;q=0.3'
,'Accept-Encoding': 'gzip, deflate'}
r = session.request('POST', url, data=parameters, headers=headers)
soup = BeautifulSoup(r.json()['d'])
return soup
def scrape_recipe_ids(soup):
ids = [re.findall(r'id=(\d+)', a['href'])[0] for d in soup.find_all('div',{'class':'item'}) for a in d.find_all('a')]
print('Found {} recipes'.format(len(ids)))
return ids
def get_recipe(session, id, imgpath):
url = 'http://www.pepperplate.com/recipes/view.aspx?id={}'.format(id)
r = session.request('GET', url)
soup = BeautifulSoup(r.content)
title = soup.find(id='cphMiddle_cphMain_lblTitle').get_text().strip()
print('Downloaded "{}"'.format(title))
thumb = soup.find(id='cphMiddle_cphMain_imgRecipeThumb')
if thumb:
print('* Downloading thumbnail')
r = requests.get(thumb['src'])
m = re.search('recipes/(.+\.jpg)', thumb['src'])
with open(imgpath + '/{}'.format(m.group(1)),'wb') as img:
img.write(r.content)
return title, soup
def format_recipe(old_soup):
new_soup = BeautifulSoup('<html><head></head><body></body></html>')
thumb = old_soup.find(id='cphMiddle_cphMain_imgRecipeThumb')
if thumb:
hdr = new_soup.new_tag('img')
m = re.search('recipes/(.+\.jpg)', thumb['src'])
hdr['src'] = './img/{}'.format(m.group(1))
new_soup.body.append(hdr)
source = soup.find(id='cphMiddle_cphMain_hlSource')
title = old_soup.find(id='cphMiddle_cphMain_lblTitle').get_text().strip()
hdr = new_soup.new_tag('title')
hdr.append(title)
new_soup.head.append(hdr)
hdr = new_soup.new_tag('h1')
hdr.append(title)
new_soup.body.append(hdr)
if source:
new_soup.body.append(source)
hdr = new_soup.new_tag('h3')
hdr.append('Ingredients')
new_soup.body.append(hdr)
item = old_soup.find('ul', {'class':'inggroups'})
if item:
new_soup.body.append(item)
else:
new_soup.body.append('No ingedients listed')
hdr = new_soup.new_tag('h3')
hdr.append('Instructions')
new_soup.body.append(hdr)
item = old_soup.find('ol', {'class':'dirgroupitems'})
if item:
new_soup.body.append(item)
else:
new_soup.body.append('No instructions listed')
hdr = new_soup.new_tag('h3')
hdr.append('Notes')
new_soup.body.append(hdr)
notes = old_soup.find(id="cphMiddle_cphMain_lblNotes")
if notes:
hdr = new_soup.new_tag('pre')
hdr.append(notes.get_text())
new_soup.append(hdr)
return new_soup
def save_recipe(title, id, soup, savepath):
title = title.replace('/','_').replace('"', '').replace(':','')
with open(savepath + '/{}.{}.html'.format(title, id), 'wb') as f:
f.write(soup.prettify('latin-1'))
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Scrape recipies from Pepperplate')
parser.add_argument('username', help='Username to log in with')
parser.add_argument('password', nargs="?", default=None, help='Password to log in with. If not provided on the command line it will be requested by the program')
parser.add_argument('directory', nargs="?", default='recipes', help='Directory to which download everything. defaults to "recipes"')
args = parser.parse_args()
imgpath = os.path.join(args.directory, 'img')
if not os.path.exists(imgpath):
os.makedirs(imgpath)
session = pp_login(args.username, args.password)
page = 0
soup = pp_get_page(session,page)
ids = scrape_recipe_ids(soup)
while len(ids) > 0:
for id in ids:
time.sleep(1) #sleep 1 second between requests to not mash the server
title, soup = get_recipe(session, id, imgpath)
soup = format_recipe(soup)
save_recipe(title, id, soup, args.directory)
page += 1
soup = pp_get_page(session,page)
ids = scrape_recipe_ids(soup)