无法使用selenium自带的操作进行定位时,使用JS的脚本进行操作
execute_script
测试代码
from selenium.webdriver.common.by import By
from test_selenium.base import Base
import time
class TestJS(Base):
def test_js_scroll(self):
self.driver.get('https://www.baidu.com/')
self.driver.find_element(By.ID, 'kw').send_keys('selenium测试')
ele = self.driver.execute_script('return document.getElementById("su")')
ele.click()
time.sleep(3)
self.driver.execute_script("document.documentElement.scrollTop=1000")
time.sleep(3)
self.driver.find_element(By.XPATH, '//*[@id="page"]/div/a[10]').click()
time.sleep(3)
结果
修改时间控件,去除时间上readonly的属性
测试代码
import pytest
from selenium.webdriver.common.by import By
from test_selenium.base import Base
import time
class TestJS(Base):
def test_datetime(self):
self.driver.get('https://www.12306.cn/index/')
time.sleep(5)
self.driver.execute_script('a=document.getElementById("train_date");a.removeAttribute("readonly")')
self.driver.execute_script("document.getElementById('train_date').value='2023-08-01'")
time.sleep(3)
print(self.driver.execute_script("return document.getElementById('train_date').value"))
结果
时间已经修改了,不过现在这个日期的框已经不是readonly了