【问题标题】:Get tab name in Chrome with Playwright使用 Playwright 在 Chrome 中获取标签名称
【发布时间】:2023-01-27 02:26:25
【问题描述】:

我正在尝试使用 playwright 获取选项卡名称,但我的代码只输出页面 url。

例如,我想转到https://www.rottentomatoes.com/ 并打印选项卡上显示的名称:

烂番茄:电影/电视节目/电影预告片...

我尝试使用 page.title 和其他一些选项,但它不起作用。

from playwright.sync_api import sync_playwright

website = "https://www.rottentomatoes.com/"


p = sync_playwright().start()
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto(website)
print(page.content)
print(page.inner_text)
print(page.title)
print(page.context)

我的输出是:

<bound method Page.content of <Page url='https://www.rottentomatoes.com/'>>
<bound method Page.inner_text of <Page url='https://www.rottentomatoes.com/'>>
<bound method Page.title of <Page url='https://www.rottentomatoes.com/'>>

【问题讨论】:

  • 这些是方法,需要用括号调用它们,例如print(page.title())。请参阅the docs page 的“用法”部分

标签: python selenium playwright


【解决方案1】:

正如其他用户在 cmets 中提到的那样。您需要在方法 inner_text(Selector) 中将选择器作为参数传递以获取值。

from playwright.sync_api import sync_playwright

website = "https://www.rottentomatoes.com/"


p = sync_playwright().start()
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto(website)
print(page.inner_text("rt-header-nav[slot='nav-dropdowns'] [slot='movies']  a[slot='link']"))
print(page.inner_text("rt-header-nav[slot='nav-dropdowns'] [slot='tv']  a[slot='link']"))
print(page.inner_text("rt-header-nav[slot='nav-dropdowns'] [slot='trivia']  a[slot='link']"))

这将在控制台中打印。

MOVIES
TV SHOWS
MOVIE TRIVIA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多