Web scraping אחראיResponsible web scraping
HTML, BeautifulSoup, robots.txt, תנאי שימוש וקצב בקשות.
HTML, BeautifulSoup, robots.txt, terms of use and request rate.
01איך נראה דף מבפניםWhat a page looks like inside
כשאין API, אפשר לקרוא את הדף עצמו: זה גירוד רשת. כל דף בנוי מHTML: תגיות שעוטפות תוכן ויוצרות עץ. לכל תגית יכולים להיות מאפיינים כמו class. כדי לגלות את המבנה, בדפדפן לוחצים קליק ימני על פריט ובוחרים Inspect. כך נראה דף התרגול שלנו (חנות מומצאת, shelf-practice.example):
When there's no API, you can read the page itself: that's web scraping. Every page is built from HTML: tags that wrap content and form a tree. Tags can have attributes like class. To discover the structure, right-click an item in the browser and choose Inspect. Here's our practice page (an invented shop, shelf-practice.example):
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Shelf practice store</title></head>
<body>
<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>
...HTML הוא כמו בובות בבושקה: כל תגית יכולה להכיל תגיות אחרות, ובתוכן עוד. מגרדים זה לפתוח בדיוק את הבובות שצריך.
HTML is like Russian nesting dolls: every tag can hold others, and those hold more. Scraping means opening exactly the dolls you need.
מנסים לחלץ נתונים עם split על טקסט HTML.
Trying to extract data by splitting raw HTML text.
html = '<p class="price">₪59.90</p>\n<p class="price" >₪42.00</p>'
prices = [part.split("</p>")[0] for part in html.split('<p class="price">')[1:]]
assert len(prices) == 2, f"found {len(prices)} prices: one extra space in the HTML broke the split"Traceback (most recent call last):
File "/Users/you/python-course/split.py", line 3, in <module>
assert len(prices) == 2, f"found {len(prices)} prices: one extra space in the HTML broke the split"
^^^^^^^^^^^^^^^^
AssertionError: found 1 prices: one extra space in the HTML broke the splitAssertionError: found 1 prices: ...: HTML לא מסודר כמו שנדמה, ורווח קטן שובר הכול. מפרקים עם BeautifulSoup.AssertionError: found 1 prices: ...: HTML is messier than it looks, and one small space breaks everything. Parse with BeautifulSoup.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02BeautifulSoupBeautifulSoup
BeautifulSoup הופך מחרוזת HTML לעץ שאפשר לחפש בו. find מחזיר את האלמנט הראשון שמתאים, find_all את כולם. מתוך אלמנט, get_text(strip=True) נותן את הטקסט הנקי, ו-tag["data-pages"] את ערך המאפיין.
BeautifulSoup turns an HTML string into a tree you can search. find returns the first matching element, find_all returns all of them. From an element, get_text(strip=True) gives the clean text, and tag["data-pages"] the attribute's value.
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")
first = soup.find("li", class_="book")
print(first.b.get_text(), "|", first["data-pages"])
for li in soup.find_all("li", class_="book"):
print(li.b.get_text(strip=True), "-", li.i.get_text(strip=True), li.get("data-pages", "?"))Dune | 412 Dune - Frank Herbert 412 Emma - Jane Austen 474 Matilda - Roald Dahl ?
BeautifulSoup הוא כמו תוכן עניינים לדף: במקום לקרוא הכול מההתחלה, קופצים ישר לפרק שמחפשים.
BeautifulSoup is like a table of contents for a page: instead of reading from the start, jump straight to the chapter you want.
ניגשים למאפיין שלא קיים בתגית.
Reading an attribute the tag doesn't have.
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")
for li in soup.find_all("li"):
print(li["data-pages"])412
474
Traceback (most recent call last):
File "/Users/you/python-course/soup.py", line 10, in <module>
print(li["data-pages"])
~~^^^^^^^^^^^^^^
File "/usr/local/lib/python3.13/site-packages/bs4/element.py", line 2484, in __getitem__
return self.attrs[key]
~~~~~~~~~~^^^^^
KeyError: 'data-pages'KeyError: 'data-pages': ל-Matilda אין מאפיין כזה. משתמשים ב-li.get("data-pages"), שמחזיר None במקום לקרוס.KeyError: 'data-pages': Matilda has no such attribute. Use li.get("data-pages"), which returns None instead of crashing.03בוררי CSSCSS selectors
בוררי CSS הם אותה שפה שבה מעצבים דפים, והם הדרך הקצרה לתאר מה רוצים: .price לפי class, #shelf לפי id, ורווח אומר "בתוך". select מחזיר רשימה ו-select_one את הראשון. ב-Inspect בדפדפן יש גם Copy → Copy selector.
CSS selectors are the same language used to style pages, and the short way to describe what you want: .price by class, #shelf by id, and a space means "inside". select returns a list and select_one the first. In the browser's Inspect there's also Copy → Copy selector.
from bs4 import BeautifulSoup
html = """
<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>
"""
soup = BeautifulSoup(html, "html.parser")
titles = [a.get_text() for a in soup.select("article.book h3 a")]
prices = [float(p.get_text().lstrip("₪")) for p in soup.select("article.book .price")]
print(titles)
print(prices, sum(prices))
print(soup.select_one("a.next")["href"])['Dune', 'Emma', 'Matilda', 'The BFG'] [59.9, 42.0, 38.5, 36.0] 176.4 page-2.html
בורר CSS הוא כמו כתובת למשלוח: עיר, רחוב, בית, דירה. ככל שמפרטים יותר, מגיעים בדיוק לדלת הנכונה.
A CSS selector is like a delivery address: city, street, building, flat. The more specific, the more exactly you reach the right door.
בורר שלא מוצא כלום, ואז ניגשים לתוצאה.
A selector that finds nothing, then using the result.
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(soup.select_one(".price").get_text())Traceback (most recent call last):
File "/Users/you/python-course/select.py", line 9, in <module>
print(soup.select_one(".price").get_text())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_text'AttributeError: 'NoneType' object has no attribute 'get_text': select_one החזיר None כי אין .price בדף הזה. בודקים את הבורר ב-Inspect, ובקוד בודקים None.AttributeError: 'NoneType' object has no attribute 'get_text': select_one returned None because this page has no .price. Check the selector in Inspect, and check for None in code.גם בלי BeautifulSoup אפשר לראות את הרעיון: מחפשים תבנית.
Even without BeautifulSoup you can see the idea: look for a pattern.
import re
html = "<h2>Dune</h2><h2>Emma</h2>"
titles = re.findall(r"<h2>(.*?)</h2>", html)
print(titles)['Dune', 'Emma']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04להביא דף אמיתיFetching a real page
בפועל מביאים את הדף עם requests (מפגש 22) ומעבירים את r.text ל-BeautifulSoup. מנומס להציג את עצמכם בכותרת User-Agent. כמו במפגש 22: כאן התשובה הוקלטה מראש, ולתרגול אמיתי יש אתרים שנבנו בדיוק בשביל זה, כמו books.toscrape.com.
In practice you fetch the page with requests (session 22) and pass r.text to BeautifulSoup. It's polite to introduce yourself in a User-Agent header. As in session 22: the reply here was recorded in advance, and for real practice there are sites built exactly for this, like books.toscrape.com.
import requests
from bs4 import BeautifulSoup
HEADERS = {"User-Agent": "shelf-course-bot/1.0 (learning project)"}
def get_books(url):
r = requests.get(url, headers=HEADERS, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")
books = []
for art in soup.select("article.book"):
books.append({
"title": art.h3.a["title"],
"price": float(art.select_one(".price").get_text().lstrip("₪")),
"stars": art.select_one(".rating")["class"][1],
"in_stock": "In stock" in art.select_one(".stock").get_text(),
})
return books, soup.select_one("a.next")
books, nxt = get_books("https://shelf-practice.example/")
for b in books:
print(b)
print("next:", nxt["href"] if nxt else None){'title': 'Dune', 'price': 59.9, 'stars': 'Five', 'in_stock': True}
{'title': 'Emma', 'price': 42.0, 'stars': 'Three', 'in_stock': True}
{'title': 'Matilda', 'price': 38.5, 'stars': 'Five', 'in_stock': False}
{'title': 'The BFG', 'price': 36.0, 'stars': 'Four', 'in_stock': True}
next: page-2.htmlלהציג User-Agent זה כמו להזדהות בכניסה לבניין: השומר יודע מי נכנס ולמה, וקל לו יותר לאשר.
Sending a User-Agent is like signing in at a building's front desk: the guard knows who's coming and why, and is happier to let you in.
ממירים מחיר עם סימן מטבע.
Converting a price that still has its currency sign.
print(float("₪59.90"))Traceback (most recent call last):
File "/Users/you/python-course/fetch.py", line 1, in <module>
print(float("₪59.90"))
~~~~~^^^^^^^^^^
ValueError: could not convert string to float: '₪59.90'ValueError: could not convert string to float: '₪59.90': מנקים קודם: .lstrip("₪") (או replace).ValueError: could not convert string to float: '₪59.90': clean it first: .lstrip("₪") (or replace).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05כמה עמודים ושמירהSeveral pages and saving
אתרים מחלקים רשימות לעמודים. לולאת while מביאה עמוד, אוספת, ומחפשת קישור next. הקישור הוא לרוב יחסי (page-2.html), ו-urljoin הופך אותו לכתובת מלאה. בסוף שומרים הכול ל-CSV, כמו במפגש 21.
Sites split lists into pages. A while loop fetches a page, collects, and looks for a next link. The link is usually relative (page-2.html), and urljoin turns it into a full address. Finally save everything to CSV, as in session 21.
import csv
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
url = "https://shelf-practice.example/"
rows = []
while url:
soup = BeautifulSoup(requests.get(url, timeout=10).text, "html.parser")
for art in soup.select("article.book"):
rows.append({"title": art.h3.a["title"], "author": art.select_one(".author").get_text()})
nxt = soup.select_one("a.next")
url = urljoin(url, nxt["href"]) if nxt else None
time.sleep(0.1)
with open("books.csv", "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=["title", "author"])
w.writeheader()
w.writerows(rows)
print(len(rows), "books saved")
print(open("books.csv", encoding="utf-8").read())6 books saved title,author Dune,Frank Herbert Emma,Jane Austen Matilda,Roald Dahl The BFG,Roald Dahl The Hobbit,J. R. R. Tolkien Persuasion,Jane Austen
לעבור עמודים זה כמו לדפדף בקטלוג: קוראים עמוד, מחפשים "המשך בעמוד הבא", ועוצרים כשאין יותר.
Paging is like leafing through a catalogue: read a page, look for "continued on the next page", and stop when there's none.
מחברים כתובת יחסית ידנית ושוברים אותה.
Joining a relative address by hand and breaking it.
base = "https://shelf-practice.example/books/"
next_href = "/page-2.html"
url = base + next_href
assert url == "https://shelf-practice.example/page-2.html", f"built {url}"Traceback (most recent call last):
File "/Users/you/python-course/crawl.py", line 4, in <module>
assert url == "https://shelf-practice.example/page-2.html", f"built {url}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: built https://shelf-practice.example/books//page-2.htmlAssertionError: built https://shelf-practice.example/books//page-2.html: כתובת שמתחילה ב-/ נמדדת מהשורש. urljoin(base, next_href) עושה את זה נכון.AssertionError: built https://shelf-practice.example/books//page-2.html: an address starting with / is measured from the root. urljoin(base, next_href) does it right.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06לגרד באחריותScraping responsibly
גירוד פוגש אנשים אמיתיים מהצד השני. כללי התנהגות: אם יש API, משתמשים בו. קוראים את robots.txt ואת תנאי השימוש של האתר. שולחים בקשה בקצב אנושי (שנייה ומעלה בין בקשות), שומרים במטמון כדי לא לבקש פעמיים, לא אוספים מידע אישי, ולא מפרסמים תוכן של אחרים כאילו הוא שלכם. פייתון אפילו יודעת לקרוא robots.txt בעצמה:
Scraping meets real people on the other side. Etiquette: if there's an API, use it. Read the site's robots.txt and terms of use. Request at a human pace (a second or more between requests), cache so you never ask twice, don't collect personal data, and don't publish others' content as your own. Python can even read robots.txt by itself:
import requests
from urllib.robotparser import RobotFileParser
text = requests.get("https://shelf-practice.example/robots.txt", timeout=10).text
print(text)
rp = RobotFileParser()
rp.parse(text.splitlines())
for path in ["/", "/page-2.html", "/admin/users"]:
print(path, rp.can_fetch("shelf-course-bot", "https://shelf-practice.example" + path))
print("delay:", rp.crawl_delay("shelf-course-bot"))User-agent: * Disallow: /admin/ Crawl-delay: 1 / True /page-2.html True /admin/users False delay: 1
לגרד אתר זה כמו להיכנס לספרייה ציבורית: מותר לקרוא ולרשום, אבל לא לסחוב את כל המדפים בבת אחת או להיכנס לחדר הצוות.
Scraping a site is like visiting a public library: you may read and take notes, but not haul away every shelf at once or walk into the staff room.
לולאה בלי השהיה ששולחת מאות בקשות בשנייה.
A loop with no pause that sends hundreds of requests a second.
import time
start = time.perf_counter()
sent = 0
while time.perf_counter() - start < 0.01:
sent += 1
assert sent < 5, f"{sent} requests in 10 ms would hammer the server: add time.sleep(1) between requests"Traceback (most recent call last):
File "/Users/you/python-course/polite.py", line 6, in <module>
assert sent < 5, f"{sent} requests in 10 ms would hammer the server: add time.sleep(1) between requests"
^^^^^^^^
AssertionError: 112699 requests in 10 ms would hammer the server: add time.sleep(1) between requestsAssertionError: בלי השהיה, תוכנית קטנה נראית לשרת כמו התקפה, ועלולים לחסום אתכם. מוסיפים time.sleep (לפחות לפי Crawl-delay).AssertionError: without a pause, a small program looks like an attack to the server, and you may be blocked. Add time.sleep (at least the Crawl-delay).סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.