常用的 XPath 语法示例(结合Playwright)

396 阅读1分钟

以下是常用的 XPath 语法和 Playwright 中的示例代码,并展示如何获取元素内容:

示例网页源码

html

<html>
  <body>
    <div id="container">
      <h1>Welcome</h1>
      <p class="intro">This is an introduction.</p>
      <ul>
        <li><a href="/home">Home</a></li>
        <li><a href="/about">About Us</a></li>
        <li><a href="/contact">Contact</a></li>
      </ul>
      <div class="footer">
        <span>&copy; 2024 Example</span>
      </div>
    </div>
  </body>
</html>

1. 选取根节点

xpath

/html/body
python

page.locator("/html/body").text_content()
# 输出:  <body> ... </body>

2. 选取所有子节点

xpath

/html/body/*
python

page.locator("/html/body/*").all_text_contents()
# 输出: ['Welcome', 'This is an introduction.', 'Home', 'About Us', 'Contact', '&copy; 2024 Example']

3. 选取任意层级的特定节点

xpath

//div
python

page.locator("//div").all_text_contents()
# 输出: ['Welcome', 'This is an introduction.', 'Home', 'About Us', 'Contact', '&copy; 2024 Example']

4. 根据属性选取节点

xpath

//div[@id="container"]
python

page.locator('//div[@id="container"]').text_content()
# 输出: WelcomeThis is an introduction.HomeAbout UsContact

5. 选取包含特定文本的节点

xpath

//h1[text()="Welcome"]
python

page.locator('//h1[text()="Welcome"]').text_content()
# 输出: Welcome

6. 选取包含部分文本的节点

xpath

//p[contains(text(), "introduction")]
python

page.locator('//p[contains(text(), "introduction")]').text_content()
# 输出: This is an introduction.

7. 根据索引选取节点

xpath

(//li)[2]
python

page.locator('(//li)[2]').text_content()
# 输出: About Us

8. 选取节点的属性值

xpath

//a[@href="/contact"]
python

page.locator('//a[@href="/contact"]').get_attribute("href")
# 输出: /contact

9. 使用父子关系选取节点

xpath

//ul/li
python

page.locator('//ul/li').all_text_contents()
# 输出: ['Home', 'About Us', 'Contact']

10. 选取包含特定子节点的父节点

go

```xpath
//div[span]
```
```python
page.locator('//div[span]').text_content()
# 输出: WelcomeThis is an introduction.HomeAbout UsContact
```