剧作家 Python :如何获取仅当鼠标悬停在另一个输入元素上时才显示的警告元素?

Playwright Python : How do I get the warning element that is displayed only when mouse is hovered over another input element?

提问人:Wider Spider 提问时间:6/24/2023 最后编辑:Wider Spider 更新时间:6/26/2023 访问量:260

问:

我有一个输入字段,当鼠标悬停在该字段上时,会显示带有文本的警告。现在我想获取这个警告元素,并最终执行一个类似 .expect(warning_element).to_have_text("Please enter a valid value.")

重现代码:

**app.py : **

from flask import Flask

app = Flask(__name__)


@app.route('/')
def serve_html():
    html_content = """
    <!DOCTYPE html>
<html>
<head>
  <style>
    .warning {
      display: block;
      color: red;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <label for="inputField">Text Input:</label>
  <input type="text" id="inputField">

  <script>
    const inputField = document.getElementById('inputField');
    let warningMessage;

    inputField.addEventListener('mouseover', () => {
      if (!warningMessage) {
        warningMessage = document.createElement('p');
        warningMessage.classList.add('warning');
        warningMessage.textContent = 'Please enter a valid value.';
        inputField.insertAdjacentElement('afterend', warningMessage);
      } else {
        warningMessage.style.display = 'block';
      }
    });

    inputField.addEventListener('mouseout', () => {
      if (warningMessage) {
        warningMessage.style.display = 'none';
        warningMessage.remove();
        warningMessage = undefined;
      }
    });
  </script>
</body>
</html>
    """
    return html_content


if __name__ == '__main__':
    app.run()

**test_hover.py : **

from playwright.sync_api import sync_playwright

def test_hover_element():
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto("http://127.0.0.1:5000/")
        # Add code to locate the input field and hover over it
        input_field_selector = 'input#inputField'
        input_field = page.wait_for_selector(input_field_selector)
        input_field.hover()
        page.wait_for_timeout(5000)
        # Add code to wait for the additional text element to appear
        additional_text_selector = '.warning'
        additional_text = page.wait_for_selector(additional_text_selector)

        # Check if the additional text element is displayed
        is_displayed = additional_text.is_visible()
        if is_displayed:
            print("Additional text is displayed on hover!")
        else:
            print("Additional text is not displayed on hover.")

        browser.close()

test_hover_element()

其他详细信息 : Python 3.11.3 中文文档 Playwright 版本 1.35.0

当我尝试运行上面提供的代码时,它给出了一个.playwright._impl._api_types.TimeoutError: Timeout 30000ms exceeded.

日志还提到:

等待 locator(“.warning”) 可见

还有一件事,我在 headless=True 和 headless=False 模式下都这样做了。在headless=False中,我可以看到警告没有显示。但是,当我手动将鼠标移到输入上时,我可以看到悬停文本,在这种情况下,测试运行成功。然而,这违背了使用剧作家实现自动化的目的。

另外,请注意,我添加只是为了查看警告文本是否以 headless=False 模式显示。page.wait_for_timeout(5000)

此外,我没有使用 ,而是尝试:input_field.hover()

1)

box = input_field.bounding_box()
page.mouse.move(box["x"]+box["width"]/2, box["y"]+box["height"]/2)
box = input_field.bounding_box()
page.mouse.click(box["x"]+box["width"]/2, box["y"]+box["height"]/2)

input_field.dispatch_event('hover')

javascript chromium 剧作家 -python

评论


答:

0赞 candre 6/26/2023 #1

我修改了您的代码以使用定位器而不是wait_for_selector,这不是必需的,因为 locator() 方法会自动等待选择器可见。它似乎按预期运行和执行,无论是有头还是无头。我还添加了一个期望有文本。

from playwright.sync_api import sync_playwright, expect


def test_hover_element():
    with sync_playwright() as playwright:
        browser = playwright.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto('http://127.0.0.1:5000/')

        input_field = page.locator('input#inputField')
        warning_text = page.locator('.warning')

        input_field.hover()

        if warning_text.is_visible():
            print('Additional text is displayed on hover!')
            expect(warning_text).to_have_text('Please enter a valid value.')
        else:
            print('Additional text is not displayed on hover.')

        browser.close()


test_hover_element()