2023最新版Selenium 4.6.0語法快速入門
簡(jiǎn)介
Selenium是一款強(qiáng)而有力的前端應(yīng)用測(cè)試工具,也非常適合搭配Python作為網(wǎng)絡(luò)爬蟲的工具;Selenium可以模擬使用者所有瀏覽器操作的動(dòng)作,包括輸入文本、點(diǎn)擊按鈕及拖拽進(jìn)度條等。有鑑于新版的Selenium 4與舊版的語法有若干明顯的差異,特別撰寫本文來與朋友們釐清并分享。
安裝
安裝Selenium套件
pip install selenium
安裝WebDriver
可以去這裡下載WebDriver,注意要與你的Chrome瀏覽器版本相同。下載并解壓縮后會(huì)得到一個(gè)chromedriver.exe的可執(zhí)行檔,建議將這個(gè)檔案複製到你的Python項(xiàng)目資料夾下,可以避免路徑的問題。
瀏覽網(wǎng)頁
1 from selenium import webdriver 2 from selenium.webdriver.chrome.service import Service 3 4 service = Service('./chromedriver') # 設(shè)定chromedriver路徑 5 driver = webdriver.Chrome(service = service) 6 driver.get('https://www.baidu.com') # 瀏覽百度網(wǎng)站首頁 7 print(driver.title) # 百度一下,你就知道
查找單一元素
""" <html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" /> </form> </body> </html> """ login_form = driver.find_element(By.ID, 'loginForm') # 用ID查找 username = driver.find_element(By.NAME, 'username') # 用NAME查找 username = driver.find_element(By.XPATH, "//input[@name='username']") #用XPATH查找
""" <html> <body> <h2>Welcome!</h2> <p class="content">Are you a stranger here?</p> <a href="continue.html">Continue</a> <a href="cancel.html">Cancel</a> </body> </html> """ continue_link = driver.find_element(By.LINK_TEXT, 'Continue') # 用超鏈接文本查找 continue_link = driver.find_element(By.PARTIAL_LINK_TEXT, 'Cont') # 用部分超鏈接文本查找 heading = driver.find_element(By.TAG_NAME, 'h2') # 用標(biāo)籤名稱查找 content = driver.find_element(By.CLASS_NAME, 'content') # 用Class名稱查找 content = driver.find_element(By.CSS_SELECTOR, 'p.content') # 用CSS選擇器查找
查找多個(gè)元素
返回值將會(huì)是一個(gè)列表(list)。login_form = driver.find_elements(By.ID, 'loginForm') # 用ID查找 username = driver.find_elements(By.NAME, 'username') # 用NAME查找 username = driver.find_elements(By.XPATH, "//input[@name='username']") #用XPATH查找 continue_link = driver.find_elements(By.LINK_TEXT, 'Continue') # 用超鏈接查找 continue_link = driver.find_elements(By.PARTIAL_LINK_TEXT, 'Cont') # 用部分超鏈接查找 heading = driver.find_elements(By.TAG_NAME, 'h2') # 用標(biāo)籤名稱查找 content = driver.find_elements(By.CLASS_NAME, 'content') # 用Class名稱查找 content = driver.find_elements(By.CSS_SELECTOR, 'p.content') # 用CSS選擇器查找
屬性值
attribute_value = element.get_attribute('attribute-name') # 取得"attribute-name"的屬性值"attribute_value"
預(yù)期條件
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) element = wait.until(EC.visibility_of_element_located((By.ID, 'my-element-id'))) # 最多等待10秒讓元素變?yōu)榭梢?/span> elements = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'my-class'))) # 最多等待10秒,讓所有元素都可見
等待
顯式等待
顯式等待用于指示 webdriver 在移動(dòng)到自動(dòng)化腳本中的其他步驟之前等待特定條件。
from selenium.webdriver.support import expected_conditions as EC # expected_conditions模塊用于指定要等待的條件 driver.get("https://www.example.com") element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "example-id"))) # WebDriverWait方法用于指定驅(qū)動(dòng)程序和等待的最長(zhǎng)時(shí)間,本例中一旦找到元素并可點(diǎn)擊,腳本就會(huì)繼續(xù)執(zhí)行。 element.click()
隱式等待
隱式等待是被應(yīng)用在嘗試識(shí)別當(dāng)前不可用的元素時(shí),指示 webdriver 在特定時(shí)間內(nèi)輪詢 DOM(文檔對(duì)象模型)。
driver.implicitly_wait(10) # 設(shè)定隱式等待10秒 driver.get("https://www.example.com") element = driver.find_element_by_id("example-id") # 在此示例中,為Web驅(qū)動(dòng)程序的整個(gè)生命周期設(shè)置了10秒的隱式等待。這意味著如果未找到元素,驅(qū)動(dòng)程序?qū)⒌却疃?0秒然后拋出異常。如果在10秒內(nèi)找到元素,腳本將繼續(xù)執(zhí)行。
單選按鈕&復(fù)選框
radio_button.click() # 選擇單選按鈕 if not checkbox.is_selected(): checkbox.click() # 選中或取消選中復(fù)選框
下拉列表
# 選擇下拉列表中的選項(xiàng) dropdown.select_by_visible_text("Option 1") # 或者 dropdown.select_by_value("value_1") # 或者 dropdown.select_by_index(0) """ 需要注意的是,如果下拉列表不允許多選,則只能選擇一個(gè)選項(xiàng)。如果下拉列表允許多選,則可以使用select_by_visible_text、select_by_value或select_by_index方法選擇多個(gè)選項(xiàng)。如果想取消選中已選擇的選項(xiàng),可以使用deselect_by_visible_text、deselect_by_value或deselect_by_index方法來取消選擇。如果想取消選擇所有選項(xiàng),則可以使用deselect_all方法。 """
Cookies
driver.get("https://www.example.com") cookie = {'name': 'example_cookie', 'value': '1234'} driver.add_cookie(cookie) # 給瀏覽器增加一個(gè)Cookie example_cookie = driver.get_cookie('example_cookie') # 以Cookie的名稱取得Cookie print(example_cookie) cookies = driver.get_cookies() # 從瀏覽器取得所有Cookie print(cookies) driver.delete_cookie('example_cookie') # 以Cookie的名稱刪除Cookie driver.delete_all_cookies() # 刪除所有的Cookie driver.refresh() # 刷新網(wǎng)頁
前后瀏覽
driver.get('https://www.baidu.com') driver.get('https://world.taobao.com') driver.back() # 向后瀏覽 print(driver.title) # 百度一下,你就知道 driver.forward() # 向前瀏覽 print(driver.title) # Taobao | 淘寶 - 花更少淘到寶
動(dòng)作鏈
from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys action = ActionChains(driver) action.move_to_element(element).click().perform() # 移至element并點(diǎn)擊 action.context_click(element).perform() # 移至element并以右鍵點(diǎn)擊 action.drag_and_drop(source_element, target_element).perform() # 將source_element拖放到target_element action.click(element).perform() # 點(diǎn)擊element action.double_click(element).perform() # 雙擊element action.key_down(Keys.CONTROL).send_keys("s").perform() #按下"Ctrl+S" action.send_keys("Hello, world!").perform() # 在當(dāng)前文字框輸入"Hello, world!" action.send_keys_to_element(element, "Hello, world!").perform() # 在element文字框輸入"Hello, world!" action.send_keys_to_element(element, Keys.ENTER).perform() # 在element文字框輸入"ENTER"
表單
driver.get('https://www.baidu.com') driver.find_element(By.ID, 'kw').send_keys('Python') # 在文字框輸入"Python" driver.find_element(By.ID, 'su').submit() # 提交表單
滾動(dòng)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 滾動(dòng)至頁面底部 driver.execute_script("window.scrollBy(0, 500)") # 將頁面向下滾動(dòng)500像素
框架
driver.switch_to.frame("my-frame") # 通過名稱或ID切換到框架"my-frame" element = driver.find_element(By.CSS_SELECTOR, "div.my-element") print(element.text) driver.switch_to.default_content() # 切換回主框架
JavaScript
driver.execute_script("alert('Hello, world!');") # 執(zhí)行JavaScript
窗口
driver = webdriver.Chrome() # 創(chuàng)建一個(gè)瀏覽器實(shí)例 driver.execute_script("window.open('');") # 打開一個(gè)新的窗口 handles = driver.window_handles # 獲取所有窗口句柄 driver.switch_to.window(handles[-1]) # 切換到新窗口 driver.get("https://www.google.com") # 在新窗口中搜索內(nèi)容 search_box = driver.find_element_by_name("q") search_box.send_keys("Selenium") search_box.send_keys(Keys.RETURN) driver.close() # 關(guān)閉當(dāng)前窗口 driver.switch_to.window(handles[0]) # 切換回原始窗口
截圖
driver.save_screenshot('logo.png')
無頭瀏覽器
from selenium.webdriver.chrome.options import Options options = Options() options.headless = True driver = webdriver.Chrome(options = options)
關(guān)閉
driver.close() # 關(guān)閉當(dāng)前窗口 driver.quit() # 關(guān)閉瀏覽器

浙公網(wǎng)安備 33010602011771號(hào)