selenium 執行js指令碼
阿新 • • 發佈:2021-06-29
使用 selenium 直接在當前頁面中進行js互動
使用selenium 執行 Js 指令碼
要使用 js 首先要知道 js 怎麼用,現在舉個簡單得例子,就用12306舉例子, 它的首頁日期選擇框是隻能手動去選擇對應得時間,因為他是 readonly 屬性,要改為自
動選擇得話,就需要通過 js 去修改。在控制檯中我們可以簡單得進行操作,如圖:
使用selenium的話,思路是一樣的,先將readonly屬性通過js去掉,然後執行js將它的時間日期改掉,程式碼如下
# Base 為上一章節的base.py預設繼承下來的東西 from base import Base import pytest import time class TestJs(Base): def test_js(self): url = 'https://www.12306.cn/index/' self.driver.get(url) date_js = 'document.getElementById("train_date").removeAttribute("readonly")' self.driver.execute_script(date_js) time.sleep(2) date_js2 = 'document.getElementById("train_date").value="2024-06-30"' self.driver.execute_script(date_js2) # ss = self.driver.find_element_by_xpath('//*[@id="train_date"]').text # print(f'更改之後當前的日期為:{ss}') if __name__ == '__main__': pytest.main(["-vs", "test_chromjs.py"])