如何用Playwright简洁定位Streamlit编写的Selectbox元素?附代码
简洁定位Streamlit Selectbox元素(Playwright实现)
场景说明
测试页面基于Streamlit框架开发,核心代码如下:
import streamlit as st st.selectbox('select pypi:', ['a', 'b', 'c'], 0)
原Playwright定位代码采用冗长的XPath,不仅可读性差,页面结构变动时还容易失效:
from playwright.sync_api import Playwright, sync_playwright, expect def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("http://localhost:8501/") page.wait_for_timeout(1000) page.locator('//*[@id="root"]/div[1]/div[1]/div/div/div/section/div/div[1]/div/div/div/div/div/div[1]').select_option('a') page.wait_for_timeout(1000) # --------------------- context.close() browser.close() with sync_playwright() as playwright: run(playwright)
简洁实现方案
Streamlit会为st.selectbox生成带有aria-label属性的select元素,属性值就是你设置的标签文本。基于这一点,我们可以用两种简洁方式定位:
方法1:使用get_by_label直接匹配标签文本(推荐)
这是Playwright提供的语义化定位方法,可读性和稳定性最优:
from playwright.sync_api import Playwright, sync_playwright, expect def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("http://localhost:8501/") # 直接通过标签文本定位selectbox并选择选项 page.get_by_label("select pypi:").select_option('a') page.wait_for_timeout(1000) context.close() browser.close() with sync_playwright() as playwright: run(playwright)
方法2:通过aria-label属性定位
如果需要更精确的属性匹配,可以直接定位带有对应aria-label的select元素:
from playwright.sync_api import Playwright, sync_playwright, expect def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto("http://localhost:8501/") # 通过aria-label属性定位selectbox page.locator('select[aria-label="select pypi:"]').select_option('a') page.wait_for_timeout(1000) context.close() browser.close() with sync_playwright() as playwright: run(playwright)
优势说明
- 可读性强:直接关联业务标签文本,无需记忆复杂的页面结构路径
- 稳定性高:页面结构变动时,只要标签文本不变,定位就不会失效
内容的提问来源于stack exchange,提问作者fan zhou
相关产品推荐
相关产品推荐

