selenium瀏覽器自動化測驗工具 進階使用
目錄- selenium瀏覽器自動化測驗工具 進階使用
- 相關資料
- 配置相關
- 基本操作
- 使用技巧
相關資料
# selenium 支持谷歌,火狐驅動等,但一般使用谷歌的較多,這里我們主要介紹谷歌的相關配置及使用
# 谷歌驅動下載地址:
- http://npm.taobao.org/mirrors/chromedriver/
# 學習網站
- http://www.testclass.net/selenium_python
配置相關
from selenium import webdriver # 驅動
from selenium.webdriver.common.by import By # 定位by
from selenium.webdriver.common.keys import Keys # 鍵盤鍵操作
from selenium.webdriver.chrome.options import Options # 瀏覽器配置方法
from selenium.common.exceptions import TimeoutException # 加載超時例外
from selenium.webdriver.support.ui import WebDriverWait # 顯式等待
from selenium.webdriver.support import expected_conditions as EC # 可以組合做一些判斷
chrome_options = Options() # selenium配置引數
chrome_options.add_argument('--no-sandbox') # 解決DevToolsActivePort檔案不存在的報錯(目前沒遇到過)
chrome_options.add_argument('--disable-dev-shm-usage') # 解決DevToolsActivePort檔案不存在的報錯(目前沒遇到過)
chrome_options.add_argument('--headless') # 無頭模式(沒有可視頁面)
chrome_options.add_argument('start-maximized') # 螢屏最大化
chrome_options.add_argument('--disable-gpu') # 禁用gpu加速 防止黑屏
ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0'
chrome_options.add_argument('user-agent=' + ua) # 瀏覽器設定UA
chrome_options.add_experimental_option('w3c', False) # 設定已手機模式啟動需要的配置
chrome_options.add_argument('--disable-infobars') # 禁用提示測驗
chrome_options.add_experimental_option('useAutomationExtension', False) # 去掉開發者警告
chrome_options.add_experimental_option('excludeSwitches',
['enable-automation']) # 規避檢測 window.navigator.webdriver
chrome_options.add_argument( r'--user-data-dir={}'.format('C:\\Users\\pc\\AppData\\Local\\Temp\\scoped_dir13604_1716910852\\Def')) # 加載本地用戶目錄,讀取和加載的比較耗時
caps = {
'browserName': 'chrome',
'loggingPrefs': {
'browser': 'ALL',
'driver': 'ALL',
'performance': 'ALL',
},
'goog:chromeOptions': {
'perfLoggingPrefs': {
'enableNetwork': True,
},
'w3c': False,
},
} # 獲取selenium日志相關配置
driver = webdriver.Chrome(desired_capabilities=caps, chrome_options=chrome_options) # 實體化selenium配置
driver.set_page_load_timeout(60) # 頁面加載超時時間
driver.set_script_timeout(60) # 頁面js加載超時時間
driver.set_window_size(1920, 1080) # 設定視窗解析度大小
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
}) # 規避檢測配合'excludeSwitches', ['enable-automation']使用 window.navigator.webdriver (瀏覽器控制臺輸出 undefined 說明設定成功)注意新開啟視窗不生效
基本操作
# 訪問某個頁面
driver.get('www.baidu.com')
# 也可以這也寫
url = 'www.baidu.com'
driver.get(url)
# 等待加載時間 設定
- 強制等待 不論頁面是否加載完成,都往下執行 (看情況使用)
import time
url = 'www.baidu.com'
driver.get(url)
time.sleep(10) # 等待頁面加載時間
xxx后續操作
- 顯式等待 (推薦)
driver.get('www.xxx.com')
try:
xp = '//*[@id="lg_loginbox"]' # 這里可以用別的定位運算式,我比較習慣使用xpath
WebDriverWait(driver, 30).until(EC.visibility_of_all_elements_located((By.XPATH, xp)))
# driver是瀏覽器句柄 30(單位秒)是等待時間 By.XPATH使用定位元素的方法 xp是定位運算式
# 30內 會輪詢查看這個這個元素是否存在 如果30秒,這個元素還是沒有,就會拋出TimeoutException例外
except TimeoutException:
mg = '登錄("//*[@id="lg_loginbox"]")元素加載失敗!'
print(mg)
xxx后續操作
- 隱式等待 相當于設定全域的等待,在定位元素時,對所有元素設定超時時間 (看情況使用)
driver.implicitly_wait(10) # 10為等待秒數
url = 'www.baidu.com'
driver.get(url)
# 定位頁面元素
- xpath定位
xp = '//div[@id=gg]' # 注意盡量不要直接在瀏覽器復制,而且頁面有的時候會改動容錯性不高,定位也效率低
driver.find_element_by_xpath(xp)
- css屬性定位
driver.find_element_by_css_selector("#su") # 找到id='su'的標簽
- By定位 使用的前提是需要匯入By類:
from selenium.webdriver.common.by import By
具體語法如下:
find_element(By.ID,"kw") # id
find_element(By.CLASS_NAME,"s_ipt") # 類名
find_element(By.TAG_NAME,"input") # 標簽定位
find_element(By.LINK_TEXT,u" 新聞 ") # 超鏈接
find_element(By.PARTIAL_LINK_TEXT,u" 新 ") # 超鏈接
find_element(By.XPATH,"//*[@class='bg s_btn']") # xp
find_element(By.CSS_SELECTOR,"span.bg s_btn_wr>input#su") # css
# 點擊操作 (首先定位到這個元素且這個元素必須是加載出來的情況下,在執行點擊操作)
- 第一種 (某些情況下可能會報錯,比如點擊不在可視區域的元素)
driver.find_element_by_xpath('//div[@id=gg]').click()
- 第二種 使用js出發點擊事件 (推薦)
element = driver.find_element_by_xpath("//div[@id=gg]")
driver.execute_script("arguments[0].click();", element)
- 第三種 使用動作鏈操作
element = driver.find_element_by_xpath("//div[@id=gg]")
webdriver.ActionChains(driver).move_to_element(element ).click(element ).perform()
# 輸入值操作
- 第一種
driver.find_element_by_xpath('//input[@id=name]').send_keys('小胖妞')
- 第二種 呼叫js
js_code = """document.getElementById(id="mat-input-0").value = 'https://www.cnblogs.com/guokaifeng/archive/2020/11/15/123456'"""
driver.execute_script(js_code)
# 獲取標簽的 text
driver.find_element_by_xpath('//*[@id="page_3"]/div[5]/div/span[2]/span').text
# selenium 呼叫js代碼
js_code = "console.log('愛你')"
driver.execute_script(js_code)
# 動作鏈操作 ActionChains (完成一系列操作,比如滑鼠拖拽,選中后點擊等)
click(on_element=None) ——單擊滑鼠左鍵
click_and_hold(on_element=None) ——點擊滑鼠左鍵,不松開
context_click(on_element=None) ——點擊滑鼠右鍵
double_click(on_element=None) ——雙擊滑鼠左鍵
drag_and_drop(source, target) ——拖拽到某個元素然后松開
drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某個坐標然后松開
key_down(value, element=None) ——按下某個鍵盤上的鍵
key_up(value, element=None) ——松開某個鍵
move_by_offset(xoffset, yoffset) ——滑鼠從當前位置移動到某個坐標
move_to_element(to_element) ——滑鼠移動到某個元素
move_to_element_with_offset(to_element, xoffset, yoffset) ——移動到距某個元素(左上角坐標)多少距離的位置
perform() ——執行鏈中的所有動作
release(on_element=None) ——在某個元素位置松開滑鼠左鍵
send_keys(*keys_to_send) ——發送某個鍵到當前焦點的元素
send_keys_to_element(element, *keys_to_send) ——發送某個鍵到指定元素
例子:
"""
動作鏈:
- 一系列連續的動作
- 在實作標簽定位時,如果發現定位的標簽是存在于iframe標簽之中的,則在定位時必須執行一個
"""
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
driver.switch_to.frame('iframeResult')
div_tag = driver.find_element_by_id('draggable')
# 拖動 = 點擊+滑動
action = ActionChains(driver)
action.click_and_hold(div_tag)
for i in range(5):
# perform 讓動作鏈立即執行
action.move_by_offset(17, 2).perform()
sleep(0.5)
action.release()
sleep(1.5)
driver.quit()
# 視窗切換
window = driver.current_window_handle # 獲取當前操作的視窗
driver.switch_to.window() # 切換到某個視窗
- 兩個視窗,切換操作
window = driver.current_window_handle # 獲取當前操作的視窗
handles = driver.window_handles # 獲取當前視窗句柄集合(串列型別)
next_window = None # 要切換的視窗
for handle in handles: # 回圈找到與當前視窗不相等的 next_window 進行賦值
if handle != window:
next_window = handle
driver.switch_to.window(next_window) # 切換到 next_window 進行操作
...后續在next_window的操作
# 截圖
- 截取視窗圖片
driver.save_screenshot('./main.png') # 截取的是視窗大小的圖片 ./main.png 是圖片路徑
- 截取元素圖片 (驗證碼之類的)
driver.save_screenshot('./main.png') # 截取視窗圖片
code_img_tag = driver.find_element_by_xpath('//*[@id="我是驗證碼"]')
location = code_img_tag.location # 圖片坐標(左下,右上) {'x': 1442, 'y': 334}
size = code_img_tag.size # 圖片的寬高 {'height':35,'width':65}
# 裁剪的區域范圍 (獲取驗證碼的圖片)
coordinate = (int(location['x']), int(location['y']), int(location['x'] + size['width']),
int(location['y'] + size['height']))
# 使用Image裁剪出驗證碼圖片 code.png
i = Image.open('./main.png')
frame = i.crop(coordinate)
frame.save('code.png') # 保存驗證碼圖片
# 重繪瀏覽器
driver.refresh() # 跟F5效果差不多
# 獲取當前url 有時候可以用它,來判斷跳轉的路由地址是否正確
driver.current_url
# 獲取頁面html
xp = '//body' # 要獲取的html元素定位
html_text = driver.find_element_by_xpath(xp).get_attribute('innerHTML')
# 關閉視窗 driver.close() 關閉的是視窗,關閉瀏覽器請使用 driver.quit()
driver.close()
# 關閉瀏覽器
driver.quit()
使用技巧
# 判斷某個元素是否加載出來
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
try:
xp = '//*[@id="lg_loginbox"]'
WebDriverWait(driver, 30).until(EC.visibility_of_all_elements_located((By.XPATH, xp)))
# driver是瀏覽器句柄 30(單位秒)是等待時間 By.XPATH使用定位元素的方法 xp是定位運算式
# 30內 會輪詢查看這個這個元素是否存在 如果30秒,這個元素還是沒有,就會報TimeoutException
except TimeoutException:
mg = '登錄("//*[@id="lg_loginbox"]")元素加載失敗!'
print(mg)
# 判斷某個元素是否可見
def is_element_display(self, xp):
try:
element = self.driver.find_element_by_xpath(xp)
if element.is_displayed():
return True
except BaseException:
return None
"""
is_enable()、is_displayed()、isSelected() 區別
1、以下三個為布爾型別的函式
2、is_enable():用于存盤input、select等元素的可編輯狀態,可以編輯回傳true,否則回傳false
3、is_displayed():本身這個函式用于判斷某個元素是否存在頁面上(這里的存在不是肉眼看到的存在,而是html代碼的存在,某些情況元素的visibility為hidden或者display屬性為none,我們在頁面看不到但是實際是存在頁面的一些元素)
4、isSelected():很顯然,這個是判斷某個元素是否被選中,
"""
# 視窗大小設定相關
driver.maximize_window() # 視窗最大化 (頻繁啟動可能會報錯,使用無頭模式+pyinstalller打包運行,不生效,不知道為什么)
driver.set_window_size(1920, 1080) # 設定視窗解析度大小 (頻繁啟動可能會報錯,使用無頭模式+pyinstalller打包運行,生效)
chrome_options.add_argument('start-maximized') # 視窗最大化 (使用無頭模式+pyinstalller打包運行,不生效,不知道為什么)
webdriver.Chrome(r'chromedriver.exe', chrome_options=chrome_options) # 視窗
chrome_options.add_argument('start-maximized') # 視窗最大化 (使用無頭模式+pyinstalller打包運行,不生效,不知道為什么)
webdriver.Chrome(r'chromedriver.exe', chrome_options=chrome_options) # 視窗
chrome_options.add_argument('--window-size=1920,1080') # 推薦設定瀏覽器視窗大小(使用無頭模式+pyinstalller打包運行,生效)
webdriver.Chrome(r'chromedriver.exe', chrome_options=chrome_options) # 視窗
# 關于跳轉頁面是否符合預期
- 可以根據跳轉url做判斷
- 也可以根據期望頁面元素是否加載出來做判斷
# 關于關閉瀏覽器
- 注意關閉瀏覽器 要使用 driver.quit() / driver.close() 關閉的只是視窗(不會釋放記憶體)
# 關于元素定位(xpath)
- 有的網站可能使用xpath 可以標簽類名經常變動可以通過這種文本方式去定位
driver.find_element_by_xpath('//span[contains(text(),"已取消")]')
- 多條件限制 (and) 提高xpath的通用性
driver.find_element_by_xpath("//input[@type='name' and @name='kw1']")
- 多條件限制 (| 或) 提高xpath的通用性
driver.find_element_by_xpath('//div[@]/text() | //div[@]/ul/li/a/text()')
# 保持每次任務不重復打開多個瀏覽器可以使用 單例模式
class Spider(object):
# 記錄第一個被創建物件的參考
instance = None
def __new__(cls, *args, **kwargs):
# 1. 判斷類屬性是否是空物件
if cls.instance is None:
# 2. 呼叫父類的方法,為第一個物件分配空間
cls.instance = super().__new__(cls)
# 3. 回傳類屬性保存的物件參考
return cls.instance
def __init__(self):
# 每次呼叫都是同一個瀏覽器
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(r'chromedriver.exe', chrome_options=chrome_options)
作 者:郭楷豐
出 處:https://www.cnblogs.com/guokaifeng/
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角 【推薦】一下,您的鼓勵是博主的最大動力!
自 勉:生活,需要追求;夢想,需要堅持;生命,需要珍惜;但人生的路上,更需要堅強,帶著感恩的心啟程,學會愛,愛父母,愛自己,愛朋友,愛他人,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/216412.html
標籤:其他
下一篇:python工具類
