selenium笔记(六)--JavaScript脚本执行

执行JavaScript脚本

  • 为什么要执行JS脚本:
    • Webdriver对部分浏览器上的控件时不支持直接驱动的,例如滚动条、时间控件,所以我们需要执行JS脚本,间接完成这些操作
    • JS学习W3C:https://www.w3school.com.cn/js/js_examples.asp
  • selenium调用js
    • 直接执行js
      • 注意:return返回获取结果、frame嵌套
    • 定位到元素Arguments传参
      • arguments[0],传入element的第一个参数

 

from time import sleep
from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class TestJs:
    def setup(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(3)

    
    # def teardown(self):
    #     self.driver.quit()

    def test_exe_js(self):

        self.driver.get("xxx")

        """登录"""
        self.driver.find_element(By.XPATH, "//*[@name='account']").send_keys("xxx")
        self.driver.find_element(By.XPATH, "//*[@name='password']").send_keys("xxx")
        WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, "btn-save")))
        self.driver.find_element(By.ID, "btn-save").click()
        WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, "btn-search")))

        """直接执行js"""
        js = "document.getElementsByName('title')[0].value = '5510'"
        self.driver.execute_script(js)
        self.driver.execute_script("return document.getElementById('btn-search')").click()
        sleep(3)
        self.driver.back()
        sleep(3)
        js1 = "window.scrollTo(0,document.body.scrollHeight)"
        self.driver.execute_script(js1)
        js3 = 'document.getElementById("startRange").removeAttribute("readOnly")'
        self.driver.execute_script(js3)
        self.driver.find_element(By.ID, "startRange").send_keys("2020-6-1")

        """定位到元素Arguments传参执行"""
        element = self.driver.find_element(By.CSS_SELECTOR, "#btn-add")
        self.driver.execute_script("arguments[0].click();", element)

 

你可能感兴趣的:(selenium,python,测试工程师)