Playwright-Python有头/无头模式HTML结果不一致问题求助
Playwright-Python 有头/无头模式页面渲染差异问题
在使用Playwright-Python运行测试时,发现**有头模式(headed mode)与无头模式(headless mode)**下的页面/HTML存在显著差异:
- 有头模式的表现与手动操作UI完全一致
- 无头模式中,对应尺码缺货时本该禁用的「Add to Bag」按钮处于启用状态,且「Fit: True to size」提示仅在有头模式显示
核心HTML元素对比
无头模式下的按钮(启用状态):
<button aria-label="Add to bag. This button will add the item to your bag and open a dialog window. After opening press tab to move context to dialog." class="add-to-bag-with-price add-to-bag-with-selected-size pdp-mfe-ya50ik" id="AddToBag_add-to-bag__button">
有头模式下的按钮(禁用状态):
<button aria-label="Add to bag. This button will add the item to your bag and open a dialog window. After opening press tab to move context to dialog." class="add-to-bag-with-price add-to-bag-with-selected-size pdp-mfe-ya50ik" id="AddToBag_add-to-bag__button" disabled="">
截图说明
- 无头模式截图:「Add to Bag」按钮为可点击状态,页面无「Fit: True to size」提示
- 有头模式截图:「Add to Bag」按钮呈禁用状态,页面显示「Fit: True to size」提示
按钮状态判断代码
通过以下代码判断按钮状态,有头模式返回False,无头模式返回True:
if page.get_by_label("Add to bag", exact=False).is_enabled():
完整测试代码(pytest执行)
import pytest from playwright.sync_api import Page, expect def open_page(page: Page) -> None: page.goto("https://bananarepublic.gap.com/browse/product.do?pid=2666360923230") def close_dynamic_modals(page: Page) -> None: if page.get_by_test_id("dynamic-modal-content").is_visible(): print('closing promotional modal') page.get_by_label("close email sign up modal").click() # this label is used for multiple different modals if page.get_by_label("Close Survey", exact=True).is_visible(): print('closing survey modal') page.get_by_label("Close Survey", exact=True).click() # this fixture will run before every test @pytest.fixture(scope="function", autouse=True) def start(page: Page): open_page(page) close_dynamic_modals(page) def test_check_size_in_stock(page: Page): # Make sure we're at the right product page expect(page.get_by_role("heading", name="Skinny Traveler Pant")).to_be_visible() # Choose the pants color: Black page.get_by_label("Black", exact=True).check() # Click on waist size "32W" NOTE: when out of stock, the label = "Size:32W out of stock" so using exact=False page.get_by_label("Size:32W", exact=False).click() # Click on length size "30L" NOTE: when out of stock, the label = "Size:30L out of stock" so using exact=False page.get_by_label("Size:30L", exact=False).click() # Now that the desired size is selected, determine if it's in stock # 'Add to Bag' button will be disabled if it's not in stock NOTE: the label is a long sentence so using exact=False page.screenshot(path='screenshot_headless.png', full_page=True) if page.get_by_label("Add to bag", exact=False).is_enabled(): print("In stock!") assert True else: print("Out of stock!") assert False # page.screenshot(path='screenshot_headless.png')
内容的提问来源于stack exchange,提问作者user1599401
相关产品推荐
相关产品推荐

