נבנה על ידי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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-VS Code. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in VS Code. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה ההבדל בין find ל-find_all?What's the difference between find and find_all?

2. מה בוחר article.book .price?What does article.book .price select?

3. מה עושים לפני שמגרדים אתר?What do you do before scraping a site?

תרגיליםExercises

תרגילExercise 1

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

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

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

איך הפלט אמור להיראות?What should the output look like?
['Dune', 'Emma', 'Matilda']
main.py
רמזHint 1: soup.find_all("b")soup.find_all("b")
רמזHint 2: [b.get_text() for b in ...][b.get_text() for b in ...]
לפתרוןSolution
תרגילExercise 2

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
[{'title': 'Dune', 'pages': 412}, {'title': 'Emma', 'pages': 474}]
main.py
רמזHint 1: "sold" in li.get("class", [])"sold" in li.get("class", [])
רמזHint 2: int(li["data-pages"]) if li.has_attr("data-pages") else Noneint(li["data-pages"]) if li.has_attr("data-pages") else None
לפתרוןSolution
תרגילExercise 3

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
https://shelf-practice.example/books/page-2.html
https://shelf-practice.example/about
main.py
רמזHint 1: soup.find_all("a", href=True)soup.find_all("a", href=True)
רמזHint 2: בלי כפילויות בסדר: if u not in out: out.append(u).No duplicates, in order: if u not in out: out.append(u).
לפתרוןSolution
תרגילExercise 4

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
[{'title': 'Dune', 'year': '1965'}, {'title': 'Emma', 'year': '1815'}]
main.py
רמזHint 1: heads = [th.get_text(strip=True) for th in soup.find_all("th")]heads = [th.get_text(strip=True) for th in soup.find_all("th")]
רמזHint 2: לכל tr עם td: dict(zip(heads, cells)).For each tr with td: dict(zip(heads, cells)).
לפתרוןSolution
תרגילExercise 5

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

פרויקט מלווהCompanion project

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
4 page-2.html
{'title': 'Dune', 'author': 'Frank Herbert', 'price': 59.9, 'stars': 5}
scrape.py
רמזHint 1: WORDS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}WORDS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
רמזHint 2: art.select_one(".rating")["class"][1]art.select_one(".rating")["class"][1]
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

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

כתבו 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.

איך הפלט אמור להיראות?What should the output look like?
sleep 1
['Dune', 'Emma']
main.py
רמזHint 1: קבוצה seen וספירת עמודים.A seen set and a page counter.
רמזHint 2: שבירת הלולאה: אין next, ביקרנו, אסור, או הגענו ל-max_pages.Stop when: no next, already visited, forbidden, or max_pages reached.
לפתרוןSolution
אתגרChallenge 2

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

שני דפים של חנויות שונות (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.

איך הפלט אמור להיראות?What should the output look like?
{'Dune': ('B', 54.5), 'Emma': ('A', 35.0)}
main.py
רמזHint 1: פונקציה לכל חנות שמחזירה מילון כותרת → מחיר.A function per shop returning title → price.
רמזHint 2: כותרות משותפות: a.keys() & b.keys().Shared titles: a.keys() & b.keys().
לפתרוןSolution

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