请优化下面代码:from playwright.sync_api import sync_playwright import time def login(): with sync_playwright() as playwright: browser = playwright.chromium.launch(headless=False) context = browser.new_context() page = context.new_page() time.sleep(3) page.goto("https://www.csdn.net/") time.sleep(3) page.get_by_text("登录", exact=True).click() time.sleep(3) page.frame_locator('iframe[name="passport_iframe"]').get_by_text("密码登录").click() time.sleep(3) page.frame_locator('iframe[name="passport_iframe"]').get_by_placeholder("手机号/邮箱/用户名").click() time.sleep(3) page.frame_locator('iframe[name="passport_iframe"]').get_by_placeholder("手机号/邮箱/用户名").fill("18523861111")
时间: 2024-04-25 09:26:12 浏览: 168
可以使用Playwright提供的wait_for_selector方法来替换多个time.sleep方法,可以提高代码的可读性和稳定性。同时,可以将重复的代码抽象成变量或函数,以便于重复使用和维护。改写后的代码如下:
```python
from playwright.sync_api import sync_playwright
def login():
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.csdn.net/")
login_button_selector = 'text="登录"'
password_login_selector = 'text="密码登录"'
account_input_selector = 'placeholder="手机号/邮箱/用户名"'
page.wait_for_selector(login_button_selector).click()
page.wait_for_selector(password_login_selector).click()
account_input = page.wait_for_selector(account_input_selector)
account_input.click()
account_input.fill("18523861111")
```
这里使用了三个变量来存储选择器,使用wait_for_selector方法替换了time.sleep方法,提高了代码的可读性和稳定性。
阅读全文