前言
在我们使用部分网站的时候,我们会遇到进行日期选择的问题,比如我们预定火车票或者预定酒店,需要选择发车日期或者酒店的入住与退房时间。我们执行自动化测试遇到日期控件时,如果可以输入,可以使用selenium的send_keys()方法进行输入,playwright同样也可以实现对日期控件的操作,本文我们就来介绍一下playwright的日期控件操作。
日历控件
我们常见的input标签的日历控件如下图所示:
页面网址:日期控件网址
如果我们想要选择2023年5月24日的日期,可以直接点击24,代码如下:
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://wyeditor.com/layui_demo/%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4%E7%BB%84%E4%BB%B6.html")
page.locator("#LayEdit_267858").click()
page.locator("#layui-laydate1").get_by_role("cell", name="24").click()# --------------------- context.close() browser.close()</code></pre></div></div><p>当然,我们也可以选择直接输入,直接输入的代码如下:</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>python</div><div class="rno-markdown-code-toolbar-item is-num"><i class="icon-code"></i><span class="is-m-hidden">代码</span>运行次数:<!-- -->0</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div><button class="rno-markdown-code-toolbar-run"><i class="icon-run"></i><span class="is-m-hidden">Cloud Studio</span> 代码运行</button></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-python"><code class="language-python" style="margin-left:0">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://wyeditor.com/layui_demo/%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4%E7%BB%84%E4%BB%B6.html")
page.locator("#LayEdit_267858").click()
page.locator("#LayEdit_267858").fill("2023-05-31")
page.locator("#LayEdit_267858").click()# --------------------- context.close() browser.close()
with sync_playwright() as playwright:
run(playwright)
read-only的日历控件处理
部分的日历控件是有read-only属性的,比如12306网站的日历控件,是不能直接输入内容的,我们要进行输入,就需要先将read-only属性移除,通常我们可以通过js命令先移除该属性。代码如下:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto('http://127.0.0.1:8000/users/userinfo/')
# 去掉元素的readonly属性
js1 = 'document.getElementById("birth_day").removeAttribute("readonly");'
page.evaluate(js1)
# 直接给输入框赋值
js2 = 'document.getElementById("birth_day").value="1999-12-31";'
page.evaluate(js2)
page.pause()
context.close()
browser.close()</code></pre></div></div><h4 id="30grd" name="%E6%80%BB%E7%BB%93">总结</h4><p>本文主要介绍了playwright对日历控件的处理,playwright与selenium一样,支持对日历控件的操作,同时也可以使用js脚本实现对read-only属性的操作。</p>