【问题标题】:Run playwright in interactive mode in Python在 Python 中以交互模式运行 playwright
【发布时间】:2022-08-22 02:57:31
【问题描述】:

我正在使用剧作家使用 Python 来抓取页面。我知道如何使用脚本来做同样的事情,但我是在交互模式下尝试的。

from playwright.sync_api import Playwright, sync_playwright, expect
import time

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    page = context.new_page()
    page.goto(\"https://www.wikipedia.org/\")

    context.close()
    browser.close()
with sync_playwright() as playwright:
    run(playwright)

我试图在交互模式下这样做:

>>> from playwright.sync_api import Playwright, sync_playwright, expect
>>> playwright = sync_playwright()
>>> browser = playwright.chromium.launch(headless=False)

但这给了我一个错误:

Traceback (most recent call last):
  File \"C:\\Users\\hpoddar\\AppData\\Local\\Programs\\Python\\Python310\\lib\\idlelib\\run.py\", line 578, in runcode
    exec(code, self.locals)
  File \"<pyshell#2>\", line 1, in <module>
AttributeError: \'PlaywrightContextManager\' object has no attribute \'chromium\'

标签: python web-scraping chromium playwright playwright-python


【解决方案1】:

使用.start() 方法:

>>> from playwright.sync_api import Playwright, sync_playwright, expect
>>> playwright = sync_playwright().start()
>>> browser = playwright.chromium.launch(headless=False)
>>> page = browser.new_page()

或者,如果您只想要一个交互式浏览器,而不关心交互式 shell,您也可以使用 wait_for_timeout 函数(仅适用于 Page 对象)并将超时设置为高值:

from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.wait_for_timeout(10000)

【讨论】:

  • 有没有像sync_playwright().stop() 这样的方法?
  • @Himanshuman 就做playwright.stop()
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 2022-11-22
  • 2012-12-14
  • 2018-12-15
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 2010-12-19
相关资源
最近更新 更多