0Pricing
Web Scraping & Bots · 课时

使用 XPath 稳健选择

了解 XPath 这一功能强大的语言,用于导航 XML 和 HTML 文档并获取高度精准的数据。

使用 XPath 稳健选择 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 稳健选择」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。

「使用 XPath 稳健选择」这节课中我会学到什么?

了解 XPath 这一功能强大的语言,用于导航 XML 和 HTML 文档并获取高度精准的数据。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web Scraping & Bots 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 XPath 稳健选择」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web Scraping & Bots 课中编写并运行代码吗?

能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理复杂 HTML 结构
  2. 使用 CSS 选择器精准提取
  3. 使用 XPath 稳健选择
  4. 从 HTML 表格提取数据
← 返回 Web Scraping & Bots