selenium并不是万能的,有时候页面上操作无法实现的,这时候就需要借助JS来完成了。

一、执行js代码

例如
from selenium import webdriver import os driver = webdriver.Chrome() driver.get('https://www.baidu.com/') jsCode = 'return document' driver.execute_script(jsCode)

二、python对象与js代码混合使用(js占位符)

例如
driver = webdriver.Chrome() driver.get('https://www.12306.cn/index/') wait = WebDriverWait(driver, 30) located = ['id', 'train_date'] train_date = wait.until(expected_conditions.presence_of_element_located(located)) # js 占位符 arguments jsCode = """arguments[0].readOnly = false; arguments[0].value = '2022-06-03';""" driver.execute_script(jsCode, train_date) time.sleep(5) driver.quit()

三、使用js操作滚动条

例如
driver = webdriver.Chrome() driver.get('https://www.12306.cn/index/') # js 操作滚动条 # 向下滚动100个px # jsCode = """window.scrollTo(0, 100)""" # 滚动到最底部 jsCode = """window.scrollTo(0, window.body.scrollHeight)""" driver.execute_script(jsCode)

四、将元素滚动到可视范围内

例如
driver = webdriver.Chrome() driver.get('https://www.12306.cn/index/') # 等待找到元素 wait = WebDriverWait(driver, 10) located = ['xpath', '//ul[@class="travel-train-list"]//li[1]//a'] elem = wait.until(expected_conditions.presence_of_element_located(located)) # 执行location_once_scrolled_into_view方法滚动到元素所在位置 elem.location_once_scrolled_into_view time.sleep(5) driver.quit()