File size: 14,125 Bytes
bc2554a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec684bb
bc2554a
ec684bb
bc2554a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
maa_jericho_scraper.py
~~~~~~~~~~~~~~~~~~~~~~~

This script scrapes object records from the Museum of Archaeology
and Anthropology (MAA) collection website at the University of
Cambridge. It now also offers a Gradio-powered web interface so that
records can be gathered and downloaded without using the command line.

The scraper targets the search results for a user-provided keyword
(default: "jericho") and collects detailed object pages containing
fields such as Accession Number, Description, Place, Period, Source,
Department, Reference Numbers, Cultural Affiliation, Material, Local
Term, Measurements and a series of Events.

Usage (CLI mode):
    python maa_jericho_scraper.py --mode cli --keyword jericho --max-objects 100 --output jericho_objects.csv

Usage (Gradio UI):
    python maa_jericho_scraper.py

Options:
    --keyword: search keyword for filtering objects (default: jericho)
    --max-objects: number of object pages to scrape (default: 100)
    --output: path to the CSV file to write (default: jericho_objects.csv)
    --start-id: starting numeric object identifier for fallback scraping
    --mode: "cli" to run headless, "gradio" (default) to launch the UI

Requirements:
    - Python 3.7+
    - requests
    - beautifulsoup4
    - gradio (for the UI)

Note:
    This script is provided for educational purposes. Always review
    and respect the terms of use of any website you scrape. Use
    responsibly and avoid overwhelming the target servers with rapid
    requests.
"""

import argparse
import csv
import io
import re
import sys
import tempfile
import time
from typing import Dict, List, Optional, Tuple

import requests
from bs4 import BeautifulSoup

try:
    import gradio as gr
except Exception:  # pragma: no cover - import guard for optional dependency
    gr = None  # type: ignore[assignment]

BASE_URL = "https://collections.maa.cam.ac.uk"
SEARCH_PATH = "/objects/"
DEFAULT_KEYWORD = "jericho"


def get_search_page(session: requests.Session, keyword: str, page_num: int) -> Optional[BeautifulSoup]:
    """Return a BeautifulSoup object for a given page of search results."""
    params = {"query": keyword, "page": page_num}
    try:
        resp = session.get(f"{BASE_URL}{SEARCH_PATH}", params=params, timeout=30)
        resp.raise_for_status()
    except Exception as exc:  # pragma: no cover - network dependent
        sys.stderr.write(f"[warning] Failed to fetch search page {page_num} for keyword '{keyword}': {exc}\n")
        return None
    return BeautifulSoup(resp.text, "html.parser")


def extract_object_links(soup: BeautifulSoup) -> List[str]:
    """Extract object page URLs from a search results page."""
    links: List[str] = []
    for a in soup.find_all("a", href=True):
        href = a.get("href") or ""
        if re.fullmatch(r"/objects/\d+/?", href):
            full_url = f"{BASE_URL}{href.rstrip('/')}/"
            if full_url not in links:
                links.append(full_url)
    return links


def parse_object_page(session: requests.Session, url: str) -> Optional[Dict[str, str]]:
    """Retrieve and parse an individual object page."""
    try:
        resp = session.get(url, timeout=30)
        resp.raise_for_status()
    except Exception as exc:  # pragma: no cover - network dependent
        sys.stderr.write(f"[warning] Failed to fetch object page {url}: {exc}\n")
        return None

    soup = BeautifulSoup(resp.text, "html.parser")
    result: Dict[str, str] = {
        "Accession No": "",
        "Description": "",
        "Place": "",
        "Period": "",
        "Source": "",
        "Department": "",
        "Reference Numbers": "",
        "Cultural Affiliation": "",
        "Material": "",
        "Local Term": "",
        "Measurements": "",
        "Events": "",
        "FM": "",
        "URL": url,
    }

    data_divs = soup.find_all("div", class_=lambda c: c and "flex-wrap" in c and "flex-md-nowrap" in c)
    for div in data_divs:
        label_p = div.find("p", class_=lambda c: c and "fw-bold" in c)
        if not label_p:
            continue
        label = label_p.get_text(strip=True).rstrip(":").strip()
        if label == "Events":
            events_container = div.find("div", class_=lambda c: c and "d-flex" in c and "flex-column" in c)
            if events_container:
                entries: List[str] = []
                for p_tag in events_container.find_all("p", class_=lambda c: c and c.startswith("col-")):
                    text = p_tag.get_text(separator=" ").strip()
                    text = re.sub(r"\s+", " ", text)
                    if text:
                        entries.append(text)
                result["Events"] = " || ".join(entries)
        else:
            value_p = label_p.find_next_sibling("p")
            if value_p:
                value_text = value_p.get_text(separator=" ").strip()
                value_text = re.sub(r"\s+", " ", value_text)
                value_text = re.sub(r";\s*", "; ", value_text)
                result[label] = value_text

    fm_tag = soup.find("p", class_=lambda c: c and c.startswith("fs-"))
    if fm_tag:
        result["FM"] = fm_tag.get_text(strip=True)
    return result


def scrape_objects(max_objects: int = 100, start_id: int = 431363, keyword: str = DEFAULT_KEYWORD) -> List[Dict[str, str]]:
    """Scrape object pages until a desired number of results is collected."""
    session = requests.Session()
    session.headers.update(
        {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/117.0",
            "Accept-Language": "en-US,en;q=0.9",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Connection": "keep-alive",
        }
    )

    search_keyword = keyword.strip() or DEFAULT_KEYWORD
    object_urls: List[str] = []
    page = 1
    while len(object_urls) < max_objects:
        soup = get_search_page(session, search_keyword, page)
        if soup is None:
            break
        new_links = extract_object_links(soup)
        if not new_links:
            break
        for link in new_links:
            if link not in object_urls:
                object_urls.append(link)
                if len(object_urls) >= max_objects:
                    break
        page += 1
        time.sleep(0.5)

    if len(object_urls) < max_objects:
        current_id = start_id
        while len(object_urls) < max_objects:
            url = f"{BASE_URL}{SEARCH_PATH}{current_id}/"
            if url not in object_urls:
                object_urls.append(url)
            current_id += 1

    results: List[Dict[str, str]] = []
    for idx, url in enumerate(object_urls[:max_objects], start=1):
        sys.stderr.write(f"[info] ({idx}/{max_objects}) Scraping {url}\n")
        data = parse_object_page(session, url)
        if data:
            results.append(data)
        else:
            results.append({"URL": url})
        time.sleep(0.5)
    return results


def collect_fieldnames(records: List[Dict[str, str]]) -> List[str]:
    fieldnames: List[str] = []
    for rec in records:
        for key in rec.keys():
            if key not in fieldnames:
                fieldnames.append(key)
    return fieldnames or ["URL"]


def records_to_csv_text(records: List[Dict[str, str]]) -> Tuple[List[str], str]:
    fieldnames = collect_fieldnames(records)
    buffer = io.StringIO()
    writer = csv.DictWriter(buffer, fieldnames=fieldnames)
    writer.writeheader()
    for rec in records:
        writer.writerow({key: rec.get(key, "") for key in fieldnames})
    return fieldnames, buffer.getvalue()


def prepare_table(records: List[Dict[str, str]], fieldnames: List[str]) -> List[List[str]]:
    return [[rec.get(field, "") for field in fieldnames] for rec in records]


def write_csv(records: List[Dict[str, str]], output_path: str) -> None:
    """Write scraped records to a CSV file."""
    _, csv_text = records_to_csv_text(records)
    with open(output_path, "w", newline="", encoding="utf-8") as f:
        f.write(csv_text)


def run_scraper_interface(max_objects: int, start_id: int, keyword: str):
    if gr is None:  # pragma: no cover - runtime guard
        raise RuntimeError("Gradio is not installed. Install it with `pip install gradio` to use the UI mode.")

    try:
        max_int = max(1, int(max_objects))
        start_int = int(start_id)
    except Exception:
        status = "Please provide valid numeric values for max objects and start ID."
        return gr.update(value=[], headers=[]), "", status

    search_keyword = (keyword or "").strip()
    if not search_keyword:
        status = "Please enter a search keyword."
        return gr.update(value=[], headers=[]), "", status

    records = scrape_objects(max_objects=max_int, start_id=start_int, keyword=search_keyword)
    fieldnames, csv_text = records_to_csv_text(records)
    table = prepare_table(records, fieldnames)
    status = f"Scraped {len(records)} object(s) for keyword '{search_keyword}'."
    return gr.update(value=table, headers=fieldnames), csv_text, status


def prepare_csv_file(csv_text: str) -> Optional[str]:
    if not csv_text:
        return None
    tmp_file = tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".csv",
        prefix="jericho_",
        mode="w",
        encoding="utf-8",
    )
    with tmp_file:
        tmp_file.write(csv_text)
    return tmp_file.name


def launch_gradio_app(
    default_max: int = 25,
    default_start: int = 431363,
    default_keyword: str = DEFAULT_KEYWORD,
) -> None:
    if gr is None:  # pragma: no cover - runtime guard
        raise RuntimeError("Gradio is not installed. Install it with `pip install gradio` to use the UI mode.")

    custom_css = """
    @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600&display=swap');
    .gradio-container {
        background: radial-gradient(circle at top, #f8f5ff 0%, #f5f7fb 55%, #eef1f6 100%);
        font-family: 'IBM Plex Sans', 'Segoe UI', sans-serif;
        color: #1f2937;
    }
    #header-card {
        border-radius: 16px;
        background: rgba(255, 255, 255, 0.85);
        box-shadow: 0 12px 24px rgba(79, 59, 169, 0.15);
        padding: 20px;
    }
    #status-card .gr-markdown {
        background: rgba(255, 255, 255, 0.9);
        padding: 12px 16px;
        border-radius: 12px;
        border-left: 4px solid #6c4ddb;
    }
    .launch-controls .gr-form{
        gap: 16px !important;
    }
    """

    # with gr.Blocks(title="MAA Jericho Scraper", css=custom_css) as demo:
    with gr.Blocks(title="MAA Jericho Scraper") as demo:
        gr.Markdown(
            """<div id='header-card'>
            <h1 style='margin-bottom: 0.4rem; color: #4f3ba9;'>MAA Jericho Scraper</h1>
            <p style='margin: 0; color: #3b3b54;'>Scrape the Museum of Archaeology and Anthropology collection for artefacts using a keyword and export the results as CSV.</p>
            </div>""",
            elem_id="header-card",
        )

        with gr.Row(elem_classes="launch-controls"):
            max_objects_input = gr.Slider(
                minimum=1,
                maximum=10000,
                value=default_max,
                step=10,
                label="Maximum objects to scrape",
            )
            start_id_input = gr.Number(
                value=default_start,
                precision=0,
                label="Fallback starting object ID",
            )
            keyword_input = gr.Textbox(
                value=default_keyword,
                label="Search keyword",
                placeholder="Try terms such as 'Jericho', 'pottery', 'beads'...",
            )

        scrape_button = gr.Button("Run scraper", variant="primary", size="lg")
        status_markdown = gr.Markdown("Ready.", elem_id="status-card")
        results_table = gr.Dataframe(
            value=[],
            datatype="str",
            label="Scraped Records",
            interactive=False,
            wrap=True,
            row_count=(0, "dynamic"),
            col_count=(0, "dynamic"),
        )
        csv_state = gr.State("")
        download_button = gr.DownloadButton(
            label="Download CSV",
            variant="secondary",
            size="lg",
        )

        scrape_button.click(
            fn=run_scraper_interface,
            inputs=[max_objects_input, start_id_input, keyword_input],
            outputs=[results_table, csv_state, status_markdown],
        )
        download_button.click(fn=prepare_csv_file, inputs=csv_state, outputs=download_button)

    demo.launch()


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Scrape MAA object pages into a CSV file or launch the Gradio UI",
    )
    parser.add_argument(
        "--keyword",
        default=DEFAULT_KEYWORD,
        help="Search keyword to filter objects (default: jericho)",
    )
    parser.add_argument(
        "--max-objects",
        type=int,
        default=100,
        help="Number of object pages to scrape when running in CLI mode (default: 100)",
    )
    parser.add_argument(
        "--start-id",
        type=int,
        default=431363,
        help="Fallback starting ID for sequential scraping",
    )
    parser.add_argument(
        "--output",
        default="jericho_objects.csv",
        help="Output CSV file path when running in CLI mode",
    )
    parser.add_argument(
        "--mode",
        choices=["cli", "gradio"],
        default="gradio",
        help="Execution mode: 'cli' for command line, 'gradio' for the web UI",
    )

    args = parser.parse_args()

    if args.mode == "cli":
        records = scrape_objects(max_objects=args.max_objects, start_id=args.start_id, keyword=args.keyword)
        write_csv(records, args.output)
        print(f"Wrote {len(records)} records to {args.output}")
    else:
        launch_gradio_app(
            default_max=args.max_objects,
            default_start=args.start_id,
            default_keyword=args.keyword,
        )


if __name__ == "__main__":
    main()