执行js脚本有两种方式一种是原始js 一种jQuery 推荐使用jQuery 根据简洁 方便
selenuim
bash
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
web=webdriver.Firefox()
web.get("https://www.12306.cn/index")
el=(By.ID,"train_date")
WebDriverWait(web,10,2).until(EC.presence_of_element_located(el))
el_se=web.find_element(*el)
#执行js 方式
# js="arguments[0].setAttribute('readonly',true)"
# web.execute_script(js,el_se)
# time.sleep(5)
# #控件如果是只读,需要删除readonly 属性
# #arguments 是参数集合
# js="var el=arguments[0]; el.removeAttribute('readonly')"
# web.execute_script(js,el_se)
#jQuery 方式 推荐
js="$('#train_date').attr('readonly',true)"
time.sleep(5)
web.execute_script(js)
time.sleep(5)
js="$('#train_date').removeAttr('readonly')"
web.execute_script(js)
time.sleep(5)
el_se.clear()
time.sleep(2)
el_se.send_keys("2024-07-15")
time.sleep(5)
web.quit()
drissionpage
bash
import time
from DrissionPage import WebPage
from DrissionPage.common import By as DBy
web_page=WebPage("d")
web_page.get("https://www.12306.cn/index")
el=(DBy.ID,"train_date")
web_page.wait.eles_loaded(el,timeout=5)
js="$('#train_date').attr('readonly',true)"
web_page.run_js(js)
time.sleep(10)
js="$('#train_date').removeAttr('readonly')"
web_page.run_js(js)
time.sleep(5)
js="$('#train_date').val('2024-7-18')"
web_page.run_js(js)
time.sleep(5)
web_page.quit()