חלק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.
הנקודות החשובותKey points
- תגיות פותחות וסוגרות:
<p>...</p>Opening and closing tags:<p>...</p> - מאפיינים:
class,hrefAttributes:class,href BeautifulSoup(html, "html.parser")BeautifulSoup(html, "html.parser")find= הראשון,find_all= כולםfind= the first,find_all= allsoup.select("article.book h3 a")soup.select("article.book h3 a").class,#id, רווח = בתוך.class,#id, a space = insiderequests.get(url, headers=...)ואז souprequests.get(url, headers=...)then soup- User-Agent שמזהה אתכםA User-Agent that identifies you
- עוקבים אחרי קישור "next" עד שנגמרFollow the "next" link until it runs out
מונחיםTerms
- HTMLHTML: השפה שבה בנויים דפי אינטרנט: תגיות כמו
<h1>,<p>,<a>שעוטפות תוכן.The language web pages are built in: tags like<h1>,<p>,<a>wrapping content. - גירוד רשת (scraping)web scraping: קריאה אוטומטית של דפי אינטרנט וחילוץ נתונים מתוכם, כשאין API.Automatically reading web pages and extracting data from them, when there's no API.
- BeautifulSoupBeautifulSoup: ספרייה שמפרקת HTML לעץ שאפשר לחפש בו.
pip install beautifulsoup4.A library that parses HTML into a tree you can search.pip install beautifulsoup4. - בורר CSSCSS selector: תבנית שבוחרת אלמנטים בדף:
article.book h3 a= קישור בתוך h3 בתוך article עם class book.A pattern that picks elements on a page:article.book h3 a= a link inside h3 inside an article with class book. - robots.txtrobots.txt: קובץ באתר שאומר לרובוטים אילו חלקים מותר לסרוק ובאיזה קצב.A file on a site telling robots which parts they may crawl and how fast.
- מאפיין HTMLHTML attribute: מידע נוסף בתוך תגית:
hrefבקישור,class,data-pages. ב-BeautifulSoup:tag["href"].Extra information inside a tag:hrefon a link,class,data-pages. In BeautifulSoup:tag["href"].
Cheatsheet
HTMLHTML
<!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">soupSoup
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>"""בורריםSelectors
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>הבאהFetching
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)עמודיםPages
import csv
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
אחריותResponsibility
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())שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
AssertionError | מנסים לחלץ נתונים עם split על טקסט HTML.Trying to extract data by splitting raw HTML text. | AssertionError: found 1 prices: ...: HTML לא מסודר כמו שנדמה, ורווח קטן שובר הכול. מפרקים עם BeautifulSoup.AssertionError: found 1 prices: ...: HTML is messier than it looks, and one small space breaks everything. Parse with BeautifulSoup. |
KeyError | ניגשים למאפיין שלא קיים בתגית.Reading an attribute the tag doesn't have. | 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. |
AttributeError | בורר שלא מוצא כלום, ואז ניגשים לתוצאה.A selector that finds nothing, then using the result. | 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. |
ValueError | ממירים מחיר עם סימן מטבע.Converting a price that still has its currency sign. | 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). |
AssertionError | מחברים כתובת יחסית ידנית ושוברים אותה.Joining a relative address by hand and breaking it. | AssertionError: 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. |
AssertionError | לולאה בלי השהיה ששולחת מאות בקשות בשנייה.A loop with no pause that sends hundreds of requests a second. | AssertionError: בלי השהיה, תוכנית קטנה נראית לשרת כמו התקפה, ועלולים לחסום אתכם. מוסיפים 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). |