/
scraper.php
352 lines (284 loc) · 12.2 KB
/
scraper.php
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
<?php
require 'scraperwiki.php';
/*/
*
* Copyright 2013 David Shumway
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contact: davidshumway@gmail.com
*
/*/
// e.g. scraperwiki::sqliteexecute("insert into swdata values (?,?,?)", array(16, "John Doe", "M"))
//var_dump(scraperwiki);
//var_dump(scraperwiki::);
//var_dump(scraperwiki::sqliteexecute);
scraperwiki::save_sqlite(array("name"), array("name" => "susan", "occupation" => "software developer"),'tasks');
echo scraperwiki::save_sqlite(array("reqname", "title"), array(array('Hi ', "Hi "),array('there','is')), 'tasks');
//scraperwiki::save_sqlite(["reqname__tasktitle"], data={"reqname__tasktitle"=>'yy', "reqname"=>"Hi there"});
//scraperwiki::save_sqlite(["reqname__tasktitle"], data={"reqname__tasktitle"=>'zz', "reqname"=>"Oh"});
exit;
// max execution time 60 seconds
//set_time_limit(60);
//scraperwiki::sqliteexecute(
// "DROP TABLE last_update"
//);
//scraperwiki::sqlitecommit();
// default SQLite table
//scraperwiki::save_sqlite(array("name"), array("name" => "susan", "occupation" => "software developer");
//ScraperWiki.save_sqlite([:name], {name: "susan", occupation: "software developer"})
//scraperwiki::sqliteexecute(
// "CREATE TABLE IF NOT EXISTS jobs (
// id INTEGER PRIMARY KEY ASC,
// title string,
// requester_id string,
// requester_name string,
// HITs_available int,
// time_posted int,
// time_last_update int,
// job_exists int,
// id_duplicate_jobs int NOT NULL DEFAULT 0,
// on_page_number int
// )"
//);
// last updates (by time())
//scraperwiki::sqliteexecute(
// "CREATE TABLE IF NOT EXISTS last_update (
// id INTEGER PRIMARY KEY ASC,
// HITs_available int,
// jobs int
// )"
//);
//echo scraperwiki::busyTimeout(120000); exit;
//scraperwiki::sqliteexecute(
// 'ALTER TABLE jobs
// ADD COLUMN on_page_number INT NOT NULL DEFAULT 1'
//);
//scraperwiki::sqliteexecute(
// 'ALTER TABLE jobs
// ADD COLUMN id_duplicate_jobs INT NOT NULL DEFAULT 0'
//);
//scraperwiki::sqliteexecute(
// 'UPDATE jobs
// SET
// id_duplicate_jobs = 1'
//);
//scraperwiki::sqliteexecute(
// 'INSERT INTO last_update (id, jobs, HITs_available)
// VALUES (1, 0, 0)'
//);
// execute
//scraperwiki::sqlitecommit();// exit;
// Example URLs to load (pages 2, 3)
//searchWords=&selectedSearchType=hitgroups&sortType=NumHITs%3A1&pageNumber=2&searchSpec=HITGroupSearch%23T%231%2310%23-1%23T%23%21%23%21NumHITs%211%21%23%21
//searchWords=&selectedSearchType=hitgroups&sortType=NumHITs%3A1&pageNumber=3&searchSpec=HITGroupSearch%23T%232%2310%23-1%23T%23%21%23%21NumHITs%211%21%23%21
// Search page 1 url to load
$url_string = 'https://www.mturk.com/mturk/viewhits?searchWords=&selectedSearchType=hitgroups&sortType=NumHITs%3A1&pageNumber=1&searchSpec=HITGroupSearch%23T%232%2310%23-1%23T%23%21%23%21NumHITs%211%21%23%21';
// NOT USING--database_ids_array: array of database ids to not delete from database
//$database_ids_array = new Array();
// number pages to scrape (depth)
$np = 20;
// debug
$last__ = '';
//
$runs = 720;
//
$countrn = 0;
// variable whether any jobs have changed since last run
$jobs_are_modified = true;
// number completed pages
$count_pages_complete = 0;
while ($countrn < $runs) {
// TODO: is a run required?/continue
// set all jobs to non-existent
if ($jobs_are_modified && $count_pages_complete == $np) {
scraperwiki::sqliteexecute(
'UPDATE jobs
SET
job_exists = 0'
);
scraperwiki::sqlitecommit();
// reset this
$jobs_are_modified = false;
}
// number completed pages (reset)
$count_pages_complete = 0;
// duplicate jobs array
$duplicate_jobs_array = array();
// loop through the search pages
for ($i = 1; $i <= $np; $i++) {
// change url string to next page
$url_string = preg_replace('/pageNumber=\d+/', 'pageNumber='.$i, $url_string);
// download page
$html_content = scraperwiki::scrape($url_string);
//if ($html_content == $last__) {
// echo 'x'; exit;
//} else $last__ = $html_content;
$html_content = str_replace("\n", "", $html_content);
//>using regex - DOM is commented out below
// preg string
$preg = '/<a class="capsulelink" href="#" id="capsule(?:.+?)">(.+?)<\/a>(?:.+?)<a href="\/mturk\/searchbar\?selectedSearchType=hitgroups&requesterId=([^&"]+)[^"]{0,}">(.+?)<\/a>(?:.+?)number_of_hits(?:.+?)(\d{2,8})/';
// match all
preg_match_all($preg, $html_content, $matches);
// HIT title
// Requester ID
// Requester Name
// HITs available (8 digits max for HITs available, i.e. 99,999,999)
// ..
$m = $matches;
// count
$c = 0;
//
if (isset($m) && count($m[1]) == 10) {
//! duplicate title, requester id/name (w/ no groupid) (ie 6 dups == 114 rather than 120 results)
//! TODO: duplicate jobs do not add/delete properly (by time posted). i.e. id_duplicate_jobs is interchangeable between duplicate jobs.
foreach ($m[1] as $k => $title) {
$t = trim($title); // title
$rid = $m[2][$c]; // requester id
$rn = $m[3][$c]; // requester name
$h = $m[4][$c]; // number of HITs [digit(s)]
$key = $t.$rid.$rn.'';
if (isset($duplicate_jobs_array[$key])) { // #misses "NULL"
//if (array_key_exists($key, $duplicate_jobs_array)) { // higher cpu load
$duplicate_jobs_array[$key]++;
} else
$duplicate_jobs_array[$key] = 0;
// is job in database?
$res = scraperwiki::select('id FROM jobs
WHERE
title = "'.sqlite_escape_string($t).'" AND
requester_id = "'.sqlite_escape_string($rid).'" AND
requester_name = "'.sqlite_escape_string($rn).'" AND
id_duplicate_jobs = '.sqlite_escape_string($duplicate_jobs_array[$key]).'
LIMIT 1
');
// job is in database
if (count($res) > 0) {
// update job's HITs_available
scraperwiki::sqliteexecute(
'UPDATE jobs
SET
HITs_available = '.$h.',
time_last_update = '.time().',
job_exists = 1,
on_page_number = '.$i.'
WHERE
id = '.$res[0]['id']
);
//overwrites
/*scraperwiki::save_sqlite(
array(),
array(
"id" => ,
"HITs_available" => $h,
"exists" => 1
),
'm'
);*/
}
// else job is not in database
else
{
// update jobs are modified
$jobs_are_modified = true;
// insert new job
scraperwiki::sqliteexecute('
INSERT INTO jobs (title, requester_id, requester_name, HITs_available, time_posted, time_last_update, job_exists, id_duplicate_jobs, on_page_number)
VALUES (
"'.sqlite_escape_string($t).'",
"'.sqlite_escape_string($rid).'",
"'.sqlite_escape_string($rn).'",
'.$h.',
'.time().',
'.time().',
1,
'.sqlite_escape_string($duplicate_jobs_array[$key]).',
'.$i.'
)
');
/*scraperwiki::save_sqlite(
array(),
array(
"title" => sqlite_escape_string($t),
"requester_id" => sqlite_escape_string($rid),
"requester_name" => sqlite_escape_string($rn),
"HITs_available" => $h,
"time_posted" => time(),
"time_last_update" => time(),
"job_exists" => 1
),
'jobs'
);*/
}
// increment preg count
$c++;
}
// increment pages complete
// pages complete++ occurs when a page has
// 10 matches
$count_pages_complete++;
}
// sleep 1 second and continue
//sleep(1);
}
// End of looped pages.
// Commit now only if jobs are modified, this will update job_exists fields before purge.
if ($jobs_are_modified) {
// update last_update table (2 fields)
scraperwiki::sqliteexecute(
'UPDATE last_update
SET
HITs_available = '.time().',
jobs = '.time().'
WHERE
id = 1'
);
}
// else update HITs_available
else
{
// update last_update table (1 field)
scraperwiki::sqliteexecute(
'UPDATE last_update
SET
HITs_available = '.time().'
WHERE
id = 1'
);
}
// execute
scraperwiki::sqlitecommit();
// wait some to finish SQL above. Wait xx1 minutexx 2 minutes.
sleep(60);
// delete old
// only when completed pages is max (all complete)
if ($jobs_are_modified && $count_pages_complete == $np) {
// delete old jobs
scraperwiki::sqliteexecute(
'DELETE FROM jobs
WHERE
job_exists = 0'
);
// save above
scraperwiki::sqlitecommit();
}
// increment
$countrn++;
// debug
//echo $jobs_are_modified."\r\n";
//echo $count_pages_complete."\r\n";
//echo $np."\r\n";
//echo time()."\r\n";
// sleep 1 more minute
sleep(60);
}
//https://scraperwiki.com/scrapers/toronto_-_call_docs_-_purchasers
function sqlite_escape_string($a) {
$a = preg_replace("/'/","''",$a);
return $a;
}
?>