נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
26
חלקPart 4: נתונים ורשתData & the web כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Web scraping אחראיResponsible web scraping

HTML, BeautifulSoup, robots.txt, תנאי שימוש וקצב בקשות.

HTML, BeautifulSoup, robots.txt, terms of use and request rate.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

כותרות מדףTitles from a page

תזכורת: מה ביקשוReminder: the task

חלצו מה-HTML הנתון את כל הכותרות (בתגית b) לרשימה והדפיסו אותה.

Extract all titles (in the b tag) from the given HTML into a list and print it.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from bs4 import BeautifulSoup

html = """<ul id="shelf">
  <li class="book" data-pages="412"><b>Dune</b> <i>Frank Herbert</i></li>
  <li class="book" data-pages="474"><b>Emma</b> <i>Jane Austen</i></li>
  <li class="book sold"><b>Matilda</b> <i>Roald Dahl</i></li>
</ul>"""
soup = BeautifulSoup(html, "html.parser")
print([b.get_text() for b in soup.find_all("b")])
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
['Dune', 'Emma', 'Matilda']

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

ספרים זמיניםAvailable books

תזכורת: מה ביקשוReminder: the task

כתבו available(html) שמחזירה רשימת מילונים {title, pages} רק לספרים שאין להם class sold. pages כ-int, או None אם אין data-pages.

Write available(html) returning dicts {title, pages} only for books without class sold. pages as int, or None if there's no data-pages.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from bs4 import BeautifulSoup

def available(html):
    soup = BeautifulSoup(html, "html.parser")
    out = []
    for li in soup.select("li.book"):
        if "sold" in li.get("class", []):
            continue
        pages = int(li["data-pages"]) if li.has_attr("data-pages") else None
        out.append({"title": li.b.get_text(strip=True), "pages": pages})
    return out

html = """<ul id="shelf">
  <li class="book" data-pages="412"><b>Dune</b> <i>Frank Herbert</i></li>
  <li class="book" data-pages="474"><b>Emma</b> <i>Jane Austen</i></li>
  <li class="book sold"><b>Matilda</b> <i>Roald Dahl</i></li>
</ul>"""
print(available(html))
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
[{'title': 'Dune', 'pages': 412}, {'title': 'Emma', 'pages': 474}]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

קישורים מלאיםFull links

תזכורת: מה ביקשוReminder: the task

כתבו links(html, base) שמחזירה את כל ה-href של תגיות a כשהן הופכות לכתובות מלאות עם urljoin, בלי כפילויות, בסדר ההופעה.

Write links(html, base) returning every href of a tags turned into full addresses with urljoin, without duplicates, in order of appearance.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from urllib.parse import urljoin
from bs4 import BeautifulSoup

def links(html, base):
    out = []
    for a in BeautifulSoup(html, "html.parser").find_all("a", href=True):
        u = urljoin(base, a["href"])
        if u not in out:
            out.append(u)
    return out

html = '<a href="page-2.html">2</a> <a href="/about">about</a> <a href="page-2.html">again</a> <a>no link</a>'
for u in links(html, "https://shelf-practice.example/books/"):
    print(u)
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
https://shelf-practice.example/books/page-2.html
https://shelf-practice.example/about

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

טבלה מהדףA table from the page

תזכורת: מה ביקשוReminder: the task

כתבו table_rows(html) שמחלצת טבלת HTML (<table> עם <th> בשורה הראשונה) לרשימת מילונים, כשהכותרות הן המפתחות.

Write table_rows(html) extracting an HTML table (<table> with <th> in the first row) into a list of dicts, with the headers as keys.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from bs4 import BeautifulSoup

def table_rows(html):
    soup = BeautifulSoup(html, "html.parser")
    heads = [th.get_text(strip=True) for th in soup.find_all("th")]
    rows = []
    for tr in soup.find_all("tr"):
        cells = [td.get_text(strip=True) for td in tr.find_all("td")]
        if cells:
            rows.append(dict(zip(heads, cells)))
    return rows

html = "<table><tr><th>title</th><th>year</th></tr><tr><td>Dune</td><td>1965</td></tr><tr><td>Emma</td><td>1815</td></tr></table>"
print(table_rows(html))
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
[{'title': 'Dune', 'year': '1965'}, {'title': 'Emma', 'year': '1815'}]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 26: איסוף רשימה מאתר תרגולShelf, step 26: collecting a list from a practice site

תזכורת: מה ביקשוReminder: the task

כתבו scrape_page(html) שמחזירה (books, next_href): books היא רשימת מילונים {title, author, price, stars} (price כ-float בלי ₪, stars כמספר 1–5 מהמילה באנגלית ב-class), ו-next_href הוא ה-href של a.next או None. בדיקה על דף התרגול המוקלט.

Write scrape_page(html) returning (books, next_href): books is a list of dicts {title, author, price, stars} (price as a float without ₪, stars as 1–5 from the English word in the class), and next_href is the a.next href or None. Tested on the recorded practice page.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
scrape.py
from bs4 import BeautifulSoup

WORDS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}

def scrape_page(html):
    soup = BeautifulSoup(html, "html.parser")
    books = []
    for art in soup.select("article.book"):
        books.append({
            "title": art.h3.a["title"],
            "author": art.select_one(".author").get_text(strip=True),
            "price": float(art.select_one(".price").get_text().strip().lstrip("₪")),
            "stars": WORDS[art.select_one(".rating")["class"][1]],
        })
    nxt = soup.select_one("a.next")
    return books, (nxt["href"] if nxt else None)

PAGE = """
  <h1>Shelf practice store</h1>
  <section class="books">
    <article class="book">
      <h3><a href="books/dune.html" title="Dune">Dune</a></h3>
      <p class="author">Frank Herbert</p>
      <p class="price">₪59.90</p>
      <p class="rating Five">Five stars</p>
      <p class="stock">In stock</p>
    </article>
    <article class="book">
      <h3><a href="books/emma.html" title="Emma">Emma</a></h3>
      <p class="author">Jane Austen</p>
      <p class="price">₪42.00</p>
      <p class="rating Three">Three stars</p>
      <p class="stock">In stock</p>
    </article>
    <article class="book">
      <h3><a href="books/matilda.html" title="Matilda">Matilda</a></h3>
      <p class="author">Roald Dahl</p>
      <p class="price">₪38.50</p>
      <p class="rating Five">Five stars</p>
      <p class="stock">Out of stock</p>
    </article>
    <article class="book">
      <h3><a href="books/the-bfg.html" title="The BFG">The BFG</a></h3>
      <p class="author">Roald Dahl</p>
      <p class="price">₪36.00</p>
      <p class="rating Four">Four stars</p>
      <p class="stock">In stock</p>
    </article>
  </section>
  <a class="next" href="page-2.html">next</a>
"""
books, nxt = scrape_page(PAGE)
print(len(books), nxt)
print(books[0])
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
4 page-2.html
{'title': 'Dune', 'author': 'Frank Herbert', 'price': 59.9, 'stars': 5}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

זוחל מנומסA polite crawler

תזכורת: מה ביקשוReminder: the task

כתבו crawl(start, fetch, can_fetch, sleep, max_pages=10): מתחילה מ-start, מביאה כל עמוד עם fetch(url) (מחזירה HTML), אוספת כותרות (article.book h3 a → title), עוקבת אחרי a.next עם urljoin, לא מבקרת פעמיים באותה כתובת, מדלגת על כתובת ש-can_fetch(url) אוסר, וקוראת ל-sleep(1) בין עמודים (לא לפני הראשון). מחזירה את רשימת הכותרות.

Write crawl(start, fetch, can_fetch, sleep, max_pages=10): starts at start, fetches each page with fetch(url) (returns HTML), collects titles (article.book h3 a → title), follows a.next with urljoin, never visits an address twice, skips an address can_fetch(url) forbids, and calls sleep(1) between pages (not before the first). Returns the list of titles.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from urllib.parse import urljoin
from bs4 import BeautifulSoup

def crawl(start, fetch, can_fetch, sleep, max_pages=10):
    titles, seen, url = [], set(), start
    while url and url not in seen and len(seen) < max_pages and can_fetch(url):
        if seen:
            sleep(1)
        seen.add(url)
        soup = BeautifulSoup(fetch(url), "html.parser")
        titles += [a["title"] for a in soup.select("article.book h3 a")]
        nxt = soup.select_one("a.next")
        url = urljoin(url, nxt["href"]) if nxt else None
    return titles

SITE = {
    "https://s.example/": '<article class="book"><h3><a title="Dune">D</a></h3></article><a class="next" href="p2">n</a>',
    "https://s.example/p2": '<article class="book"><h3><a title="Emma">E</a></h3></article><a class="next" href="/">loop</a>',
}
print(crawl("https://s.example/", SITE.get, lambda u: True, lambda s: print("sleep", s)))
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
sleep 1
['Dune', 'Emma']

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

משווה מחיריםA price comparer

תזכורת: מה ביקשוReminder: the task

שני דפים של חנויות שונות (HTML נתון) עם אותם ספרים במבנה שונה: בחנות A div.item עם span.name ו-span.cost (59.90 ILS), בחנות B li.p עם מאפיינים data-title ו-data-price. כתבו cheapest(a_html, b_html) שמחזירה מילון כותרת → (store, price) של המחיר הזול יותר לכל ספר שמופיע בשתיהן.

Two shops' pages (given HTML) list the same books in different structures: shop A has div.item with span.name and span.cost (59.90 ILS), shop B has li.p with data-title and data-price attributes. Write cheapest(a_html, b_html) returning a dict title → (store, price) with the lower price for every book in both.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy
הפתרון המלא והפלט שלוFull solution and its output
main.py
from bs4 import BeautifulSoup

def shop_a(html):
    soup = BeautifulSoup(html, "html.parser")
    return {d.select_one(".name").get_text(strip=True): float(d.select_one(".cost").get_text().split()[0]) for d in soup.select("div.item")}

def shop_b(html):
    soup = BeautifulSoup(html, "html.parser")
    return {li["data-title"].strip(): float(li["data-price"]) for li in soup.select("li.p")}

def cheapest(a_html, b_html):
    a, b = shop_a(a_html), shop_b(b_html)
    return {t: ("A", a[t]) if a[t] <= b[t] else ("B", b[t]) for t in sorted(a.keys() & b.keys())}

A = '<div class="item"><span class="name">Dune</span><span class="cost">59.90 ILS</span></div><div class="item"><span class="name">Emma</span><span class="cost">35 ILS</span></div>'
B = '<ul><li class="p" data-title="Dune" data-price="54.5">Dune</li><li class="p" data-title="Matilda" data-price="30">M</li><li class="p" data-title="Emma" data-price="41">E</li></ul>'
print(cheapest(A, B))
פלט (תשובת השרת הוקלטה מראש)Output (server reply recorded in advance)
{'Dune': ('B', 54.5), 'Emma': ('A', 35.0)}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich