Latest / CyberCode Academy / Course 40 - Web Scraping with Python | Episode 18: Mastering HTML Parse Tree Navigation and Element Extraction with Beautiful Soup
Transcript
- 0:00Speaker 1: Imagine having just a highly specific digital superpower, not like
- 0:06Speaker 1: flying or invisibility, but the ability to instantly read, organize,
- 0:10Speaker 1: and extract exactly what you want from any web page
- 0:14Speaker 1: in the entire world.
- 0:15Speaker 2: Oh yeah, that would be I mean that really is
- 0:17Speaker 2: a superpower, right.
- 0:18Speaker 1: You just snap your fingers and you perfectly filter out
- 0:21Speaker 1: all the endless mountains of noise, you know, the pop ups,
- 0:24Speaker 1: the autoplaying ads, the chaotic formatting, the tracking scripts, all
- 0:28Speaker 1: of it, and you instantly harvest only the pure data
- 0:31Speaker 1: you actually care about.
- 0:32Speaker 2: It completely changes everything about how you interact with the Internet.
- 0:36Speaker 2: I mean, think about it. We spend hours of our
- 0:37Speaker 2: lives scrolling, manually searching for specific pieces of information across
- 0:42Speaker 2: these chaotic digital environments.
- 0:44Speaker 1: Oh absolutely, so much time just copying and pasting.
- 0:46Speaker 2: Exactly, So having a computer do all the heavy lifting
- 0:49Speaker 2: of reading, interpreting, and organizing a website for you it
- 0:52Speaker 2: isn't just convenient. It's a fund mental shift in how
- 0:56Speaker 2: you leverage the Web's underlying data. It basically turns the
- 1:00Speaker 2: highre Internet into your own personal database.
- 1:02Speaker 1: And that is exactly what we're getting into today on
- 1:05Speaker 1: this deep dive. If you ever write clicked on a
- 1:07Speaker 1: web page and hit a view source or inspect element.
- 1:12Speaker 1: You know, it looks like an absolute nightmare of brackets and.
- 1:14Speaker 2: Code, just a total mess.
- 1:16Speaker 1: Yeah, okay, let's unpack this. Our mission today is to
- 1:19Speaker 1: explore webscraping, specifically focusing on a famously powerful Python library
- 1:24Speaker 1: called beautiful soup. It essentially acts as a translator between
- 1:29Speaker 1: that messy reality of raw web code and the clean,
- 1:33Speaker 1: structured data we want to extract.
- 1:34Speaker 2: Yeah, and to really understand how beautiful soup accomplishes this translation,
- 1:38Speaker 2: you first have to look at how we fetch that data,
- 1:40Speaker 2: because you know, before we even touch the HTML, we
- 1:43Speaker 2: have to pull it from the server, right, getting the
- 1:45Speaker 2: actual files exactly. Typically, this process starts with the requests library.
- 1:49Speaker 1: And Python, So we're talking about standard GIET requests here.
- 1:52Speaker 2: Yes, exactly, When you type a URL into a web browser,
- 1:55Speaker 2: your browser sends a gt request behind the scenes, downloads
- 1:59Speaker 2: the code, and then renders it into a pretty visual
- 2:02Speaker 2: page with colors and fonts.
- 2:04Speaker 1: And layouts, all the stuff we're used to seeing, right.
- 2:07Speaker 2: But when we scrape, we bypass that visual rendering entirely.
- 2:11Speaker 2: You send a j ET request via Python, and you
- 2:14Speaker 2: are basically knocking on the server's door and saying, hey,
- 2:16Speaker 2: send me the raw text file that makes up this page.
- 2:19Speaker 1: Skip the paint job, just give me the raw materials.
- 2:21Speaker 2: Exactly, and the server responds with the raw HTML document.
- 2:25Speaker 1: But at this stage, before Beautiful Soup even gets involved,
- 2:30Speaker 1: what does that document actually look like? To the computer?
- 2:33Speaker 2: It is just one massive, contiguous string of characters.
- 2:37Speaker 1: Like just a giant block of text.
- 2:39Speaker 2: Yeah, to the computer's memory, it holds zero structural meaning,
- 2:43Speaker 2: it's just a wall of text millions of characters long.
- 2:46Speaker 2: There is no hierarchy yet.
- 2:47Speaker 1: Wow, which brings us to the blueprint of the web.
- 2:50Speaker 1: HTML is supposed to be the language of the Internet.
- 2:53Speaker 1: But Beautiful Soup doesn't just read it left or right
- 2:55Speaker 1: like a normal book, does it.
- 2:56Speaker 2: No, it can't. It builds what's known as a parse tree,
- 2:59Speaker 2: a parse right. When you feed that massive string of
- 3:04Speaker 2: raw HTML into Beautiful Soup, you have to specify a parser,
- 3:07Speaker 2: And a parser is essentially an engine that reads the text,
- 3:11Speaker 2: identifies the HTML tags, and attempts to organize it into
- 3:15Speaker 2: a hierarchical multi dimensional map.
- 3:18Speaker 1: So it's building the structure exactly.
- 3:20Speaker 2: The parse tree gives the document a rigid, logical structure
- 3:23Speaker 2: that a program can actually systematically navigate I see now.
- 3:27Speaker 1: I know lexml's often the parser of choice here, but
- 3:31Speaker 1: why XML specifically? I mean, there were standard HTML parsers
- 3:35Speaker 1: build right into Python itself, right, Why go through the
- 3:38Speaker 1: trouble to install a third party parser?
- 3:40Speaker 2: Well, the built in parsers are completely fine if you
- 3:42Speaker 2: are dealing with perfectly written, mathematically sound.
- 3:45Speaker 1: Code, which, let's be honest, never happens exactly.
- 3:48Speaker 2: The reality of the Internet is that most HTML is
- 3:50Speaker 2: just heavily duct taped together. You'll find unclosed tags, missing
- 3:53Speaker 2: body elements, stray brackets, typos from developers rushing to push updates.
- 3:58Speaker 1: It's a wild last out there, it really is.
- 4:00Speaker 2: And if you use a strict built in parser, it
- 4:02Speaker 2: will hit a missing divtag and just boom, instantly throw
- 4:05Speaker 2: a fatal error and crash your entire script.
- 4:07Speaker 1: Oh brutal. So XML is favored because it's lenient, then
- 4:12Speaker 1: how does it actually handle those errors without crashing?
- 4:15Speaker 2: It actively infers intent. So if LexML is parsing a
- 4:19Speaker 2: page and sees, say, a paragraph tag nested inside a
- 4:24Speaker 2: table row, but the table row was never officially opened
- 4:27Speaker 2: in the code, it doesn't crash.
- 4:29Speaker 1: It just figures it out.
- 4:30Speaker 2: Yeah, it retroactively creates the missing structural elements in the
- 4:34Speaker 2: parse tree to make the hierarchy mathematically sound.
- 4:37Speaker 1: That's amazing.
- 4:38Speaker 2: It's a very forgiving translator. It kind of exposes just
- 4:40Speaker 2: how messy the Internet that's infrastructure really is because it's
- 4:43Speaker 2: building a fully functional tree even out of broken raw materials.
- 4:47Speaker 1: It's like having an editor who fixes your grammar mistakes
- 4:50Speaker 1: on the fly, so the book still makes perfect sense.
- 4:52Speaker 2: That's a great way to put it.
- 4:53Speaker 1: Yeah, And once LexML builds that tree, it's often really
- 4:56Speaker 1: helpful to visualize it. I know. Beautiful Soup has a
- 4:59Speaker 1: function called soup dot pretiphi.
- 5:00Speaker 2: Right, Yes, Pretiphi is fantastic.
- 5:02Speaker 1: It takes this newly structured, autocorrected tree and prints the
- 5:05Speaker 1: HTML back out, but beautifully formatted with proper indentations in
- 5:09Speaker 1: line breaks. It just makes the hierarchy readable for the
- 5:12Speaker 1: human eye.
- 5:13Speaker 2: Again, which is incredibly useful for debugging. You can physically
- 5:17Speaker 2: see the nesting structure before you start writing your extraction code.
- 5:20Speaker 1: Right, I usually visualize this HTML structure like a set
- 5:24Speaker 1: of Russian nesting dolls.
- 5:25Speaker 2: Oh interesting, how so, Well.
- 5:27Speaker 1: Let's say we are looking at a fake e commerce
- 5:29Speaker 1: site like a novelty gift shop. Okay, sure, the biggest
- 5:33Speaker 1: wooden doll on the outside containing the whole visible page
- 5:37Speaker 1: is typically an outer div element. You open that big
- 5:40Speaker 1: dift doll, and inside you find smaller containers, maybe a logo,
- 5:44Speaker 1: a header tag that says total normal gifts, and a
- 5:47Speaker 1: massive table element containing all the products.
- 5:49Speaker 2: Right. The analogy works pretty well for the concept of containment.
- 5:52Speaker 2: But here's where it deviates from physical nesting doll. Okay,
- 5:55Speaker 2: tell me a real nesting doll only ever holds one
- 5:58Speaker 2: smaller doll, which holds one's smaller doll, and so on. True,
- 6:01Speaker 2: But an HTML container like that outer dev you mentioned
- 6:05Speaker 2: might hold five thousand differently shaped boxes at the exact
- 6:08Speaker 2: same level.
- 6:09Speaker 1: Oh wow, And some.
- 6:10Speaker 2: Of those boxes hold text while others hold images, while
- 6:14Speaker 2: others hold hidden scripts. It branches out exponentially.
- 6:17Speaker 1: Fair point. Yeah, it's nesting dolls, but they're multiplying rapidly
- 6:21Speaker 1: at every single level exactly. So if we look specifically
- 6:24Speaker 1: at that table element on our fake gift shop page,
- 6:28Speaker 1: the branching just continues. You open the table tag, find
- 6:31Speaker 1: a t body tag, and inside that you have individual
- 6:35Speaker 1: rows the price tags. Right, the roads and inside each
- 6:38Speaker 1: row you finally hit the table cells the t tags
- 6:40Speaker 1: holding the actual gift names and the prices.
- 6:43Speaker 2: Yeah, and now that we have the entire document loaded
- 6:46Speaker 2: into memory as a navigable, mathematically sound parse tree, the
- 6:50Speaker 2: challenge shifts how So well, the computer sees the structure,
- 6:54Speaker 2: but we need to tell it how to hunt down
- 6:56Speaker 2: specific data points within that sprawling branching tree.
- 7:00Speaker 1: Ah right, because extracting specific tags is great if you
- 7:03Speaker 1: want everything. But if I want the price of a
- 7:05Speaker 1: specific gift, I don't want to open every single branch
- 7:08Speaker 1: on the entire website just to find it. I need
- 7:10Speaker 1: to know how to jump straight to the data I
- 7:11Speaker 1: actually care.
- 7:12Speaker 2: About exactly, and Beautiful Soup provides a few targeted methods
- 7:15Speaker 2: for this. The fastest, most intuitive way is called dot
- 7:19Speaker 2: notation dot notation. Because beautiful Soup has turned the raw
- 7:23Speaker 2: HTML into a Python object, you can access tags directly
- 7:28Speaker 2: as properties of that object. So if you just type
- 7:31Speaker 2: soup dot title, it instantly hands you the title tag.
- 7:34Speaker 1: Oh that's easy.
- 7:35Speaker 2: Yeah, if you type soup dot tr it hands you
- 7:37Speaker 2: a table row.
- 7:38Speaker 1: Wait. Wait, if I type soup dot img to get
- 7:41Speaker 1: an image, which image does it actually give me? I
- 7:44Speaker 1: mean a webpage could have fifty different product images on it.
- 7:48Speaker 2: It gives you the very first one it encounters in
- 7:49Speaker 2: the parstree, and then it immediately stops searching.
- 7:52Speaker 1: Wait, really, that seems like a massive vulnerability. If dot
- 7:55Speaker 1: notation only grabs the first image, isn't that practically useless
- 7:59Speaker 1: for scrape an entire catalog? I mean, the first image
- 8:02Speaker 1: on most sites is just the company logo in the
- 8:04Speaker 1: top navigation bar.
- 8:06Speaker 2: It is a vulnerability if you use it for the
- 8:07Speaker 2: wrong task. Dot notation is really only designed for unique
- 8:11Speaker 2: singleton elements like the page title or the main head tag.
- 8:15Speaker 2: For bulk extraction, relying on it is a classic beginner mistake.
- 8:19Speaker 2: I actually learned this the hard way a few years
- 8:20Speaker 2: back when I first started building automated scrapers.
- 8:22Speaker 1: Oh no, what happened?
- 8:23Speaker 2: Well, I wrote a scraper for a financial data site.
- 8:27Speaker 2: I was using a variation of a basic search to
- 8:29Speaker 2: grab the first table row on the page, which always
- 8:32Speaker 2: contained the daily ticker summary I needed. Makes sense, and
- 8:35Speaker 2: it worked flawlessly for about three months. Then the site
- 8:39Speaker 2: developers quietly updated their HTML template. Oh yeah, they added
- 8:44Speaker 2: a tiny, invisible one by one pixel right at the
- 8:47Speaker 2: top of the body tag for analytics tracking, and they
- 8:51Speaker 2: wrapped it in its own hidden table structure.
- 8:53Speaker 1: Oh no, I see exactly where this is going.
- 8:55Speaker 2: My script ran every morning automatically at four am, so
- 8:59Speaker 2: instead of grabbing the financial summary, the scraper hit that
- 9:02Speaker 2: hidden analytics table row first, stop searching, and downloaded a
- 9:07Speaker 2: bunch of useless metadata attached to an invisible pixel. Oh man, yeah,
- 9:11Speaker 2: I collected absolute garbage data for a week before I
- 9:14Speaker 2: even notice the error.
- 9:15Speaker 1: That is painful, but it perfectly illustrates why we need
- 9:19Speaker 1: something more robust. Yeah, so how did you fix it?
- 9:22Speaker 1: How do you avoid the tracking pixel trap?
- 9:24Speaker 2: By transitioning to explicit search methods For single items, you
- 9:27Speaker 2: use the dot find function. It still returns only the
- 9:30Speaker 2: first match, but it's highly flexible. Flexible hab Well, you
- 9:33Speaker 2: aren't limited to just a generic tag name. You can
- 9:35Speaker 2: use regular expressions to search for structural pattern.
- 9:38Speaker 1: Meaning I can tell dot find to look for an
- 9:42Speaker 1: element that starts with the letter H followed by a digit,
- 9:45Speaker 1: and it will grab the first H one or each
- 9:47Speaker 1: two it hits, just ignoring everything else.
- 9:50Speaker 2: Correct. Or you can tell it to find the first
- 9:53Speaker 2: table row that also possesses a specific CSS class bypassing
- 9:57Speaker 2: those hidden tracking pixels entirely.
- 9:59Speaker 1: That's but for the.
- 10:01Speaker 2: Catalog scraping scenario you mentioned earlier, the true workhorse of
- 10:04Speaker 2: beautiful Soup is dot findal.
- 10:06Speaker 1: Okay, So if we use dot findal on our novelty
- 10:09Speaker 1: gift shop, beautiful Soup scans the entire perse tree from
- 10:13Speaker 1: top to bottom and gathers every single table cell on
- 10:16Speaker 1: the page. Like if there are twenty cells in the
- 10:18Speaker 1: product grid, it just hands you all.
- 10:19Speaker 2: Twenty exactly, and crucially, it returns them as a standard
- 10:23Speaker 2: Python list.
- 10:24Speaker 1: Oh nice.
- 10:25Speaker 2: This is where web scraping seamlessly merges with standard data manipulation.
- 10:29Speaker 2: Because find all outputs a standard iterable object. You just
- 10:33Speaker 2: loop through it using basic Python logic.
- 10:35Speaker 1: Right, just simple for loop. And as we iterate over
- 10:38Speaker 1: that list of table cells, we need to extract the
- 10:40Speaker 1: actual text, right because right now the data is still
- 10:43Speaker 1: wrapped in those HTML brackets. We want the name of
- 10:45Speaker 1: the novelty gif, not the TD tags surrounding it.
- 10:48Speaker 2: Yes, and this is handled by accessing the dot text
- 10:51Speaker 2: property of each element in your loop.
- 10:53Speaker 1: Just dot text.
- 10:54Speaker 2: Yep. When you query dot text, beautiful Soup acts like
- 10:58Speaker 2: a highly aggressive filter. It strips away all surrounding HTML tags.
- 11:02Speaker 2: It removes the brackets, the markers, the inline scripts, everything.
- 11:06Speaker 1: Wow, it really cleans it up.
- 11:08Speaker 2: It does. It can even be configured to strip out
- 11:10Speaker 2: extraneous white space and hidden newlines. It leaves you with
- 11:13Speaker 2: nothing but pure usable data.
- 11:15Speaker 1: So basically, dot find ol acts as the mining equipment
- 11:18Speaker 1: gathering the raw ore, and the text property acts as
- 11:21Speaker 1: the refinery, burning away the rock and handing us pure metal.
- 11:24Speaker 2: That is a perfect analogy.
- 11:26Speaker 1: But here's where it gets really interesting. Elements aren't just
- 11:29Speaker 1: dumb containers holding text. They have metadata, they have hidden instructions.
- 11:33Speaker 1: We need to look at the anatomy of the HTML
- 11:35Speaker 1: tags themselves to understand how much data is actually available
- 11:39Speaker 1: to us.
- 11:40Speaker 2: Absolutely. Up to this point we've treated tags as basic
- 11:43Speaker 2: structural boundaries. In Beautiful Soup, however, HTML elements are treated
- 11:48Speaker 2: as sophisticated objects. Specifically, they are instantiated as tag objects.
- 11:54Speaker 1: Okay, so they're objects.
- 11:56Speaker 2: Yeah, they have properties of their own, completely independent of
- 11:59Speaker 2: the texts they contain.
- 12:00Speaker 1: Let me throw out another analogy to visualize this. If
- 12:03Speaker 1: the tag itself is a physical cardboard box, the attributes
- 12:07Speaker 1: are the shipping labels slapped onto the outside of that box.
- 12:10Speaker 2: Oh I like that framing right.
- 12:12Speaker 1: The shipping labels tell the browser where the box goes,
- 12:14Speaker 1: what category belongs to, or how big it should be drawn,
- 12:17Speaker 1: all without the browser ever having to actually open the
- 12:20Speaker 1: box to see what's inside.
- 12:21Speaker 2: That's exactly it. The box might be an image tag,
- 12:24Speaker 2: but the shipping label the attribute is the CRC attribute.
- 12:28Speaker 2: That attribute contains the actual URL pointing to the server
- 12:31Speaker 2: where the image file is hosted right right. Or the
- 12:34Speaker 2: attribute might be a CSS class that tells the website's
- 12:36Speaker 2: stylesheet to render the box with a red border and
- 12:39Speaker 2: a drop shadow.
- 12:40Speaker 1: So how do we actually read those shipping labels in
- 12:43Speaker 1: our Python script?
- 12:44Speaker 2: Beautiful Soup stores all of a tag's attributes in a
- 12:47Speaker 2: dictionary data structure, So if you've saved an image tag
- 12:51Speaker 2: to a variable, you access its attributes exactly like you
- 12:55Speaker 2: would retrieve a value by its key in a normal
- 12:57Speaker 2: Python dictionary.
- 12:59Speaker 1: Just standard brack notation exactly.
- 13:01Speaker 2: You append square brackets to the variable, put the attribute
- 13:05Speaker 2: name in quotes like src, and beautiful soup retrieves the
- 13:09Speaker 2: destination URL.
- 13:11Speaker 1: Okay, but what if a tag has multiple labels of
- 13:13Speaker 1: the same type. It's pretty common for a single paragraph
- 13:17Speaker 1: tag to have multiple CSS classes attached to it to
- 13:20Speaker 1: handle complex styling, like say, it's class as highlight and
- 13:24Speaker 1: also classed is important. How does a dictionary handle multiple
- 13:27Speaker 1: values for a single key.
- 13:29Speaker 2: It's clever, beautiful soup anticipates that HTML is highly flexible
- 13:33Speaker 2: with multi valued attributes. When you query a multi valued
- 13:36Speaker 2: attribute like a class, it doesn't just concatenate the words
- 13:39Speaker 2: into one messy string.
- 13:40Speaker 1: Oh good, right.
- 13:41Speaker 2: It parses the values and returns them as a cleanly
- 13:44Speaker 2: organized Python list. You get a list containing the string
- 13:47Speaker 2: highlight and the string important, which is perfectly formatted for
- 13:50Speaker 2: conditional logic in your script.
- 13:51Speaker 1: Okay, so we have the box which is the tag object.
- 13:54Speaker 1: We have the shipping labels, which are the attributes. The
- 13:57Speaker 1: last piece of the element's anatomy is the actual item
- 14:01Speaker 1: inside the box, the string of text. Right, earlier, we
- 14:03Speaker 1: talked about extracting the pure data using the dot text property,
- 14:07Speaker 1: but I also saw another property called dot string. What
- 14:10Speaker 1: is the mechanical difference between extracting dot text and extracting
- 14:14Speaker 1: dot string.
- 14:14Speaker 2: The distinction is subtle, but it's critical for how your
- 14:17Speaker 2: script manages memory and navigation. Okay, laid on me when
- 14:21Speaker 2: you called dot text beautiful soup extracts the characters, copies
- 14:26Speaker 2: them into a new block of memory, and hands you
- 14:29Speaker 2: a standard Python string. It is dead text, dead text. Yeah,
- 14:33Speaker 2: it has been entirely severed from the htmil document. You
- 14:36Speaker 2: can analyze it, but you cannot use it to interact
- 14:39Speaker 2: with the web page structure anymore.
- 14:40Speaker 1: So it's isolated data doesn't know where it came from.
- 14:42Speaker 2: Yes, but when you call string beautiful, soup returns a
- 14:46Speaker 2: very specific object called a navigable string.
- 14:48Speaker 1: A navigable string. Why does text need to be navigable?
- 14:52Speaker 2: Because a navigable string operates as a memory pointer. It
- 14:55Speaker 2: retains its reference back to the original parse tree.
- 14:58Speaker 1: Oh icee.
- 14:59Speaker 2: It inherents only knows its position in the hierarchy, knows
- 15:02Speaker 2: which tag is its parent container and which tags are
- 15:05Speaker 2: its siblings. If you possess a navigable string, you can
- 15:08Speaker 2: pivot from the text itself right back into navigating the
- 15:11Speaker 2: HTML structure, which a standard string just cannot do.
- 15:15Speaker 1: That is fascinating. The text itself remains a tethered part
- 15:19Speaker 1: of the ecosystem exactly. Speaking of hidden elements in that ecosystem,
- 15:22Speaker 1: what about developer comments? Normal users never see them, but
- 15:26Speaker 1: developers constantly leave notes for each other hidden directly in
- 15:29Speaker 1: the HTML code.
- 15:30Speaker 2: Oh yeah, beautiful Soup doesn't ignore those comments or blindly
- 15:34Speaker 2: treat them as regular strings.
- 15:35Speaker 1: Either.
- 15:36Speaker 2: It identifies them as a distinct object type, a comment object, which.
- 15:41Speaker 1: Seems like a massive advantage for cybersecurity research or auditing. Right.
- 15:45Speaker 2: Absolutely, developers notoriously leave sensitive information in comments. They'll comment
- 15:50Speaker 2: out old blocks of code that still contain valid API keys,
- 15:53Speaker 2: or leave internal server IP addresses, or you wouldn't believe
- 15:57Speaker 2: it even temporary passwords. That's wilds Beautiful soup isolates comments
- 16:01Speaker 2: as their own object type. You can write a scraper
- 16:04Speaker 2: to bypass all the visible text and purely aggregate every
- 16:08Speaker 2: hidden comment across an entire domain in minutes.
- 16:11Speaker 1: That's so powerful. So we've covered searching for tags directly
- 16:15Speaker 1: using dot find and dot findal. We've extracted attributes and
- 16:19Speaker 1: differentiated between dead text and navigable strings. But consider this scenario.
- 16:24Speaker 1: What if the developers were just lazy. What if we're
- 16:27Speaker 1: dealing with a web page that doesn't use unique classes
- 16:29Speaker 1: or IDs. What if every single piece of data is
- 16:33Speaker 1: just wrapped in generic paragraph tags. How do we locate
- 16:37Speaker 1: our target data when direct searching is basically impossible.
- 16:40Speaker 2: This is exactly where direct searching fails and relational navigation
- 16:43Speaker 2: traversal becomes essential traversal. Right, you don't find the data
- 16:47Speaker 2: by its name, you find it by its neighborhood.
- 16:49Speaker 1: Oh, it's like knowing you on a specific house, but
- 16:51Speaker 1: none of the houses on the street have numbers. However,
- 16:54Speaker 1: you know the house you want is always exactly two
- 16:56Speaker 1: doors down from the post office.
- 16:58Speaker 2: That's the exact logic. Beautiful soup allows directional traversal through
- 17:02Speaker 2: the parse tree. You can move up the hierarchy to
- 17:05Speaker 2: parent and ancestor nodes, you can move down the tree
- 17:09Speaker 2: to children and descendant nodes, and perhaps most powerfully, you
- 17:13Speaker 2: can move sideways through sibling nodes.
- 17:16Speaker 1: Moving sideways across siblings feels like a total game changer
- 17:20Speaker 1: for generic code.
- 17:21Speaker 2: It really is incredibly efficient. Sibling traversal allows you to
- 17:25Speaker 2: move left and right across elements that share the exact
- 17:27Speaker 2: same level of hierarchy and the same parent container.
- 17:31Speaker 1: You give me an example.
- 17:32Speaker 2: Sure, let's say you're scraping a wiki article. The data
- 17:35Speaker 2: you want is in an unnamed generic paragraph, But you
- 17:38Speaker 2: know that paragraph always appears immediately after an H two
- 17:41Speaker 2: header that says early life.
- 17:42Speaker 1: Okay, so the header is my post office.
- 17:44Speaker 2: In this scenario, exactly, you don't need to search for
- 17:46Speaker 2: the paragraph. You find the unique header and then simply
- 17:49Speaker 2: command beautiful soup to select its stet next sibling.
- 17:52Speaker 1: You just slide right over to the data by passing
- 17:55Speaker 1: the generic tags entirely. That's brilliant. What about moving downwards into.
- 17:59Speaker 2: The tags and to inspect a tag's immediate contents you
- 18:03Speaker 2: use the dot content's property. If you select a top
- 18:06Speaker 2: level tag like the head tag and query its dot contents,
- 18:09Speaker 2: beautiful soup returns a list of everything nested directly inside.
- 18:13Speaker 1: It, so like the title tag, meta tags.
- 18:16Speaker 2: Yep, and even the literal line breaks that exist in
- 18:19Speaker 2: the raw HTML formatting.
- 18:20Speaker 1: Because it returns a list, I can use standard Python
- 18:24Speaker 1: index numbers to grab a specific child right index zero
- 18:27Speaker 1: gives me the first child, index one gives me the second,
- 18:30Speaker 1: and so on.
- 18:30Speaker 2: Precisely. Let's trace a real world extraction using that exact logic.
- 18:34Speaker 1: Let's do it.
- 18:34Speaker 2: Imagine you're scraping a blog. You use dot notation or
- 18:37Speaker 2: dot find to locate a specific paragraph tag. You query
- 18:41Speaker 2: dot contents to look inside it. You see the second
- 18:44Speaker 2: child in the lists, an anchor link and a tag
- 18:46Speaker 2: pointing to an external site. Right, you select that a
- 18:49Speaker 2: tag using its index number, query its attributes as a dictionary,
- 18:52Speaker 2: and extract the h ref url.
- 18:55Speaker 1: That makes total sense, But I do have a mechanical
- 18:57Speaker 1: question regarding traversing downwards. If I can use dot contents
- 19:01Speaker 1: to open a tag and see its children, and then
- 19:04Speaker 1: use dot contents on one of those children to see
- 19:07Speaker 1: its children, can you just keep chaining dot contents indefinitely
- 19:11Speaker 1: until I reach the very bottom of the text.
- 19:13Speaker 2: You cannot, and attempting to do so is a trap
- 19:16Speaker 2: that crashes a lot of scraper scripts. Really, why it
- 19:20Speaker 2: loops back to our discussion on the navigable.
- 19:22Speaker 1: String ah the text that remembers where it came from.
- 19:26Speaker 2: Yes, the pars tree is constructed of tag objects containing
- 19:29Speaker 2: other tag objects, but eventually you reach the actual text
- 19:32Speaker 2: content the navigable string. A string is not a structural container.
- 19:36Speaker 2: It cannot hold HTML.
- 19:37Speaker 1: Elements, so it has no children exactly.
- 19:39Speaker 2: Therefore, a navigal string does not possess a dot contents properly.
- 19:43Speaker 1: Because it's the absolute end of the line.
- 19:45Speaker 2: Right, if you write a loop that blindly chains dot
- 19:48Speaker 2: contents downward, the instant it hits a text string and
- 19:51Speaker 2: attempts to ask for its children, Python will throw an
- 19:54Speaker 2: attribute error and your execution just halts.
- 19:56Speaker 1: So you have to program your scraper to recognize the
- 19:59Speaker 1: difference between a tag object which can be opened and
- 20:01Speaker 1: a string object, which cannot you do. It's the difference
- 20:04Speaker 1: between opening a shipping box to find a smaller box
- 20:07Speaker 1: versus opening a box and finding a solid brick. You
- 20:10Speaker 1: can't open the brick.
- 20:11Speaker 2: That's a perfect way to internalize it. Understanding the underlying
- 20:14Speaker 2: object types is what separates a brutal script from a
- 20:17Speaker 2: really resilient automated scraper.
- 20:20Speaker 1: We have covered some serious ground today. We started by
- 20:23Speaker 1: looking at how requests fetch the raw wall of HTML
- 20:26Speaker 1: text directly from the server. We explored how lenient parsers
- 20:30Speaker 1: like lex and l air act as forgiving translators converting
- 20:34Speaker 1: the duct taped chaos of the Internet into a strictly
- 20:37Speaker 1: organized hierarchy called a parse tree.
- 20:39Speaker 2: Well, we did, and we examined the severe limitations of
- 20:42Speaker 2: dot notation and the sheer utility of finde law combined
- 20:46Speaker 2: with rejects for bulk extraction.
- 20:48Speaker 1: Yeah, we broke down element anatomy learning to read attributes
- 20:51Speaker 1: as dictionaries and distinguishing between isolated dot text and tethered
- 20:55Speaker 1: string objects.
- 20:56Speaker 2: Right.
- 20:56Speaker 1: And finally, we looked at relational traversal, navigating up to
- 20:59Speaker 1: parents down to chill using dot contents, and sliding sideways
- 21:02Speaker 1: across siblings. When direct searching isn't an option due to
- 21:05Speaker 1: generic coding.
- 21:06Speaker 2: It really is a comprehensive approach to data extraction. Once
- 21:10Speaker 2: you grasp these mechanical principles, the web transforms from a
- 21:14Speaker 2: series of visual pages into a massive, highly structured database
- 21:18Speaker 2: just waiting to be queried.
- 21:19Speaker 1: So a quick review exercise for you listening to lock
- 21:22Speaker 1: this all in think back to our discussion on hunting
- 21:25Speaker 1: down specific data.
- 21:26Speaker 2: This is a good test.
- 21:27Speaker 1: If your goal today is to write a script that
- 21:30Speaker 1: extracts every single image link from a massive scrolling blog
- 21:33Speaker 1: post containing dozens of pictures, would you rely on dot
- 21:37Speaker 1: notation or would you use findal?
- 21:40Speaker 2: Yeah, take a second to think about it.
- 21:42Speaker 1: If you chose findal, you've got the fundamentals down. Remember
- 21:45Speaker 1: the trackingpixel trap dot notation would only ever hand you
- 21:48Speaker 1: the very first image it encounters and stop searching immediately.
- 21:52Speaker 2: Beautiful soup forces us to see the hidden rigid hierarchy
- 21:56Speaker 2: behind the colorful, chaotic websites we visit every day. It
- 22:00Speaker 2: strips away the visual presentation and reveals the structural skeleton beneath.
- 22:04Speaker 2: It really does, and that leaves me with a broader
- 22:07Speaker 2: thought tom all over. If you take these concepts of parents, children,
- 22:12Speaker 2: and especially the efficiency of sideways sibling traversal and apply
- 22:16Speaker 2: them to how we structure all human knowledge, Oh wow,
- 22:19Speaker 2: right from massive corporate org charts to your own personal
- 22:22Speaker 2: digital file systems. What hidden connections or efficiencies might you
- 22:26Speaker 2: discover just by learning to look sideways?
- 22:29Speaker 1: Something to think about the next time you find yourself
- 22:31Speaker 1: navigating a sea of information. Until next time, keep exploring
- 22:34Speaker 1: the deep dive