发送JS指令操作浏览器

## DOM 文档对象模型(Document Object Model,简称DOM)
通过 JS 控制浏览器当中的页面行为。
document是DOM中的一种转换对象的方法

 通过ducument操作元素:

 通过window操作浏览器

 滚动页面

 

 滚动元素

 修改时间选择器的时间

## JS 的操作
如果出现 selenium 不支持的页面操作,通过发送 js 指令给浏览器执行。
driver.execute_script("js")
class TestDemo:
    def test_01(self):
        with webdriver.Chrome(executable_path='chromedriver_95.exe') as browser:
            browser.implicitly_wait(5)
            # 另外打开一个窗口
            # selenium 发送 JS 代码, 给浏览器执行
            browser.execute_script('window.open()')
            time.sleep(3)

滚动页面至最后,懒加载

class TestDemo:
    def test_01(self):
        with webdriver.Chrome(executable_path='chromedriver_95.exe') as browser:
            browser.implicitly_wait(5)
            browser.get('https://readhub.cn/topics')
            js = 'window.scrollTo(0, document.body.scrollHeight)'
            browser.execute_script(js)
            time.sleep(3)

修改时间选择器

class TestDemo:
    def test_01(self):
        with webdriver.Chrome(executable_path='chromedriver_95.exe') as browser:
            browser.implicitly_wait(5)
            browser.get('https://www.12306.cn/index/')

            js = """el = document.getElementById("train_date")
            el.value = "2021-11-30"
            """

            browser.execute_script(js)
            time.sleep(5)
class TestDemo:
    def test_01(self):
        with webdriver.Chrome(executable_path='chromedriver') as browser:
            browser.implicitly_wait(5)
            browser.get('https://www.12306.cn/index/')
            # 通过 python selenium 找到元素
            el = browser.find_element('id', 'train_date')
            js = 'arguments[0].value = "2021-11-30"'  # arguments[0]的用法类似于format中的{},是个占位符
            browser.execute_script(js, el)
            time.sleep(5)

 上传文件:

class TestDemo:
    def test_01(self):
        url = 'file:///D:/vip%E7%8F%AD%E7%BA%A7/py44/day38_dom%E5%AF%B9%E8%B1%A1/demo_js.html'
        with webdriver.Chrome(executable_path='chromedriver_95.exe') as browser:
            browser.implicitly_wait(5)
            browser.get(url)
            # 通过 python selenium 找到元素
            el = browser.find_element('name', 'mfile')
            el.send_keys(r'绝对路径\notes.md')

            time.sleep(3)

基本每个上传的标签都能通过xpath找到//input[@type="file"]

系统自动化

```python
from pywinauto import Desktop
app = Desktop()
dialog = app['打开'] #根据名字找到弹出窗口
dialog["Edit"].type_keys("D:\\用户.html") # 在输入框中输入值
dialog["Button"].click()
```

```python
pip install pillow==6.2.2
pip install pyautogui
time.sleep(1)
pyautogui.write('d:\\cases.xlsx')
pyautogui.press('enter', 2)
```
原文地址:https://www.cnblogs.com/wsfsd/p/15628341.html