要使用 Playwright 获取网站元素内容,您可以使用 page.textContent(selector) 方法。以下是一个扩展上面代码的示例,该示例获取网站的标题和正文内容:

from playwright.sync_api import sync_playwright

# 创建一个playwright实例
with sync_playwright() as playwright:
    # 选择要使用的浏览器类型(chromium、firefox或webkit)
    browser_type = playwright.chromium

    # 启动浏览器并创建一个新页面
    browser = browser_type.launch()
    page = browser.new_page()

    # 跳转到网站
    page.goto('https://example.com')

    # 获取网站标题
    title = page.title()
    print(f'Title: {title}')

    # 获取网站正文内容
    content = page.text_content('body')
    print(f'Content: {content}')

    # 关闭浏览器
    browser.close()

在上面的代码中,page.title() 方法用于获取网站的标题,page.text_content(selector) 方法用于获取指定选择器的元素文本内容。在示例中,我们使用 'body' 选择器来获取整个网站的正文内容,您可以根据需要更改选择器来获取特定元素的内容。

Playwright 获取网站元素内容 - 示例代码详解

原文地址: https://www.cveoy.top/t/topic/qkly 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录