selenium
Selenium 是一個用於Web應用程序測試的工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣。支持的瀏覽器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera,Edge等。這個工具的主要功能包括:測試與瀏覽器的兼容性——測試你的應用程序看是否能夠很好得工作在不同瀏覽器和操作系統之上。測試系統功能——創建回歸測試檢驗軟件功能和用戶需求。支持自動錄制動作和自動生成 .Net、Java、Perl等不同語言的測試腳本。
准備工作
-
安裝seleniumm
pip install selenium
-
下載瀏覽器驅動
Firefox瀏覽器驅動:geckodriver
Chrome瀏覽器驅動:chromedriver
需要把瀏覽器驅動放入系統路徑中,或者直接告知selenuim的驅動路徑
3.測試代碼
from selenium import webdriver
from time import sleep
def main():
# global driver
chromedriver_path = "C:\Program Files\Google\Chrome\Application\chromedriver.exe" #替換對應路徑
driver = webdriver.Chrome(executable_path="C:\Program Files\Google\Chrome\Application\chromedriver.exe") #替換對應路徑
# 打開頁面
page = driver.get('https://www.baidu.com/')
sleep(100) # 暫停100秒,防止自動關閉
if __name__ == "__main__":
main()
Selenium 教程
官方文檔:selenium
百度搜索實例
from selenium import webdriver
from time import sleep
def main():
# global driver
chromedriver_path = "C:\Program Files\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(executable_path="C:\Program Files\Google\Chrome\Application\chromedriver.exe")
# 打開頁面
page = driver.get('https://www.baidu.com/')
sleep(1)
search_input = driver.find_element_by_id('kw')
search_input.send_keys("mac pro")
btn = driver.find_element_by_id("su").click()
# btn.click()
sleep(100) # 暫停100秒,防止自動關閉
if __name__ == "__main__":
main()