selenium 执行JavaScript脚本

无法使用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了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值