0Pricing
Web Scraping & Bots · 강의

견고한 선택을 위한 XPath

XML 및 HTML 문서를 탐색하고 매우 구체적인 데이터를 검색할 수 있는 강력한 언어인 XPath를 알아봅니다.

견고한 선택을 위한 XPath은(는) CoddyKit의 무료 Web Scraping & Bots 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Scraping & Bots 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is XPath?

Welcome to XPath! It stands for XML Path Language, and it's a powerful tool for navigating and selecting nodes in XML and HTML documents.

Think of it as a specialized language for finding specific pieces of information within a web page's structure.

  • XPath is incredibly flexible for complex selections.
  • It allows navigation in any direction (up, down, sideways).
  • It's essential for robust data extraction.

XPath & the Document Tree

Before diving into syntax, let's understand how XPath "sees" a document. It views HTML/XML as a tree structure.

  • Each element, attribute, and even text is a "node" in this tree.
  • XPath expressions are like directions, guiding you from the root of the tree to the specific nodes you want to find.

This tree model allows for precise, hierarchical navigation.

Select by Tag Name

The simplest way to select elements is by their tag name. We use // to select elements anywhere in the document, or / for direct children.

For example, //h1 selects all <h1> elements.

We'll use Python's lxml library for our examples.

from lxml import html

html_doc = """
<html>
<body>
  <h1>My Product Page</h1>
  <div class="product-list">
    <h2>Product A</h2>
  </div>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Select all h1 tags
results = tree.xpath("//h1")

for element in results:
    print(element.text_content())

Targeting Elements by Attribute

Often, you need to select elements based on their attributes, like id or class. XPath uses predicates ([]) for this.

Use @attribute to refer to an attribute. For example, //div[@class='product-card'] selects all <div> elements with class="product-card".

from lxml import html

html_doc = """
<html>
<body>
  <div class="product-card" id="p1">
    <h2>Product A</h2>
  </div>
  <div class="product-card" id="p2">
    <h2>Product B</h2>
  </div>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Select div elements with class 'product-card'
results = tree.xpath("//div[@class='product-card']")

for element in results:
    print(element.get('id')) # Get the id attribute

Finding Elements by Text

XPath can also find elements based on their visible text content. This is very powerful for locating specific labels or values.

  • Use text() to refer to the direct text of an element.
  • Use contains(text(), 'part') to find elements whose text contains a specific substring.

For example, //p[text()='$19.99'] finds a paragraph with that exact price.

from lxml import html

html_doc = """
<html>
<body>
  <p class="price">$19.99</p>
  <p class="price">$29.50</p>
  <span>In Stock!</span>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Select p elements containing '$19.99'
results = tree.xpath("//p[text()='$19.99']")

for element in results:
    print(element.text_content())

Navigating Up & Down the Tree

XPath lets you move around the document tree. Use / for direct child nodes and // for any descendant.

  • div/p: Selects <p> elements that are direct children of <div>.
  • //div//p: Selects <p> elements that are descendants of any <div>, no matter how deep.
  • /parent::div: Selects the parent <div> of the current node.
from lxml import html

html_doc = """
<html>
<body>
  <div class="product-card">
    <h2>Product A</h2>
    <p class="price">$19.99</p>
  </div>
  <div class="footer">
    <p>Copyright</p>
  </div>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Find the price within a product-card
results = tree.xpath("//div[@class='product-card']/p[@class='price']")

for element in results:
    print(element.text_content())

Filtering with Positional Predicates

Predicates ([]) can also filter elements based on their position among siblings. This is useful for selecting the first, last, or specific item in a list.

  • //li[1]: Selects the first <li> element.
  • //li[last()]: Selects the last <li> element.
  • //div[position()=2]: Selects the second <div> element.
from lxml import html

html_doc = """
<html>
<body>
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Select the second list item
results = tree.xpath("//ul/li[2]")

for element in results:
    print(element.text_content())

Complex Selections with and/or

You can combine multiple conditions within a predicate using and or or to make your selections even more precise.

  • //a[@href and @class='button']: Selects <a> tags that have both an href attribute AND a class of 'button'.
  • //p[@class='price' or contains(text(), 'Sale')]: Selects paragraphs with class 'price' OR containing the text 'Sale'.
from lxml import html

html_doc = """
<html>
<body>
  <a href="/link1" class="button">Link 1</a>
  <a href="/link2">Link 2</a>
  <a class="button">Link 3</a>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Select 'a' tags that have both 'href' and 'class="button"'
results = tree.xpath("//a[@href and @class='button']")

for element in results:
    print(element.text_content())

Practical Extraction: Product Price

Let's put it all together. Imagine you want to extract the price of "Product B" from a list of products. We can combine attribute selection and hierarchy.

We'll first find the specific product card, then navigate to its price element.

from lxml import html

html_doc = """
<html>
<body>
  <div class="product-list">
    <div class="product-card" id="p1"><h2>Product A</h2><p class="price">$19.99</p></div>
    <div class="product-card" id="p2"><h2>Product B</h2><p class="price">$29.50</p></div>
    <div class="product-card" id="p3"><h2>Product C</h2><p class="price">$5.00</p></div>
  </div>
</body>
</html>
"""

tree = html.fromstring(html_doc)
# Find the price of Product B
xpath_exp = "//div[@id='p2']/p[@class='price']"
results = tree.xpath(xpath_exp)

for element in results:
    print(element.text_content())

XPath Challenge

Consider the following HTML snippet:

<div class="container">
  <ul id="main-menu">
    <li>Home</li>
    <li class="active">About Us</li>
    <li>Contact</li>
  </ul>
  <div class="content">
    <p>Welcome!</p>
    <a href="/learn">Learn More</a>
  </div>
</div>

Recap: XPath for Precision

Congratulations! You've learned the fundamentals of XPath, a highly versatile language for navigating and selecting elements in HTML and XML documents.

  • XPath uses a tree model to represent documents.
  • You can select elements by tag, attribute, text content, and position.
  • Predicates [] and operators like and/or allow for incredibly precise targeting.

Mastering XPath will significantly enhance your ability to extract exactly the data you need from complex web pages. Keep practicing!

자주 묻는 질문

“견고한 선택을 위한 XPath” 강의는 무료인가요?

네 — “견고한 선택을 위한 XPath” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Scraping & Bots 강의 전체를 잠금 해제할 수 있습니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.

“견고한 선택을 위한 XPath”에서 뭘 배우나요?

XML 및 HTML 문서를 탐색하고 매우 구체적인 데이터를 검색할 수 있는 강력한 언어인 XPath를 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 Web Scraping & Bots을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Web Scraping & Bots을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Web Scraping & Bots은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“견고한 선택을 위한 XPath” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Web Scraping & Bots 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Web Scraping & Bots 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 복잡한 HTML 구조 탐색
  2. 정밀한 CSS 선택자
  3. 견고한 선택을 위한 XPath
  4. HTML 표에서 데이터 추출하기
← Web Scraping & Bots(으)로 돌아가기