Using Playwright for Python, how do I select (or find) an element?

走远了吗. 提交于 2021-01-28 05:54:05

问题


I'm trying to learn the Python version of Playwright. See here

I would like to learn how to locate an element, so that I can do things with it. Like printing the inner HTML, clicking on it and such.

The example below loads a page and prints the HTML

from playwright import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.newPage()
    page.goto('http://whatsmyuseragent.org/')
    print(page.innerHTML("*"))
    browser.close()

This page contains an element

<div class="user-agent">
    <p class="intro-text">Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4238.0 Safari/537.36</p>
</div>

Using Selenium, I could locate the element and print it's content like this

elem = driver.find_element_by_class_name("user-agent")
print(elem)
print(elem.get_attribute("innerHTML"))

How can I do the same in Playwright?


回答1:


You can use the querySelector function, and then call the innerHTML function:

handle = page.querySelector(".user-agent")
print(handle.innerHTML())


来源:https://stackoverflow.com/questions/64303326/using-playwright-for-python-how-do-i-select-or-find-an-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!