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_argument("--proxy-server=http://110.73.2.248:8123")# 添加代理
chrome_options.add_argument("proxy-server=socks5://127.0.0.1:1080")# 加socks5代理(防止代理檢測,未使用過)
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 說明設置成功)注意新開啟窗口不生效
或者使用這個配置
chrome_options.add_argument("disable-blink-features=AutomationControlled")# 去掉了webdriver痕跡 (推薦,上邊執行js操作替換掉就行,新開啟窗口生效 )
基本操作
# 訪問某個頁面
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 = '123456'"""
driver.execute_script(js_code)
# 獲取標簽的 text
driver.find_element_by_xpath('//*[@id="page_3"]/div[5]/div/span[2]/span').text
# 獲取標簽的 屬性值
driver.find_element_by_xpath('//*[@id="page_3"]/div[5]/div/span[2]/span').get_attribute('src')
# 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效果差不多
# 定位frame標簽
# frame標簽有frameset、frame、iframe三種,frameset跟其他普通標簽沒有區別,不會影響到正常的定位,
# 而frame與iframe對selenium定位而言是一樣的,selenium有一組方法對frame進行操作。
driver.switch_to.frame('tcaptcha_iframe') # 切換到frame標簽 tcaptcha_iframe是frame標簽的id 也可以傳入標簽對象元素
xp = '//div[@id="captcha_close"]' # 對frame標簽里面的元素進行操作
ele = driver.find_element_by_xpath(xp)
driver.execute_script("arguments[0].click();", ele)
driver.switch_to.default_content() # 切換到主頁面
# 獲取當前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(),"已取消")]') # 標簽文本包含 '已取消'
driver.find_element_by_xpath('//span[text()="已取消"]') # 標簽文本等於 '已取消'
- 通過父類元素定位到兄弟元素
driver.find_element_by_xpath("//div[@class="bottom"]/../div[4]")
- 多條件限制 (and) 提高xpath的通用性
driver.find_element_by_xpath("//input[@type='name' and @name='kw1']")
- 多條件限制 (| 或) 提高xpath的通用性
driver.find_element_by_xpath('//div[@class="bottom"]/text() | //div[@class="bottom"]/ul/li/a/text()')
# 注意 driver.find_elements_by_xpath(xp) 是獲取多個元素,得到的結果為列表
# 保持每次任務不重復打開多個瀏覽器可以使用 單例模式
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)
# 針對某些需要下拉/滑動的操作 可調用js的 scrollBy 方法
js_code = "window.scrollBy(0,100);" # 0為向右滾動的像素數 100為向下滾動的像素數
self.driver.execute_script(js_code)
# 從selenium日志獲取 某個請求信息的具體操作
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('start-maximized')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu') # 防止黑屏
chrome_options.add_experimental_option('w3c', False)
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-infobars') # 禁用提示測試
chrome_options.add_experimental_option('excludeSwitches',
['enable-automation']) # 規避檢測 window.navigator.webdriver
caps = {
'browserName': 'chrome',
'loggingPrefs': {
'browser': 'ALL',
'driver': 'ALL',
'performance': 'ALL',
},
'goog:chromeOptions': {
'perfLoggingPrefs': {
'enableNetwork': True,
},
'w3c': False,
},
}
driver = webdriver.Chrome(desired_capabilities=caps, chrome_options=chrome_options)
driver.set_page_load_timeout(60) # 頁面加載超時時間
driver.set_script_timeout(60) # 頁面js加載超時時間
for log in self.driver.get_log('performance'):
x = json.loads(log['message'])['message']
if x["method"] == "Network.responseReceived":
# 獲取某個鏈接的響應信息方法
if 'www.xxx.com' in x["params"]["response"]["url"]:
response_data = json.loads(
driver.execute_cdp_cmd('Network.getResponseBody',
{'requestId': x["params"]["requestId"]})[
'body'])
return response_data # 響應信息
if x["method"] == "Network.requestWillBeSent": # 獲取某請求相關操作
if 'www.ooo.com' in x["params"]["response"]["url"]:
try:
ip = x["params"]["response"]["remoteIPAddress"]
except BaseException as p:
print(p)
ip = ""
try:
port = x["params"]["response"]["remotePort"]
except BaseException as f:
print(f)
port = ""
response.append(
{
'ip': ip,
'port': port,
'type': x["params"]["type"],
'url': x["params"]["response"]["url"],
'requestId': x["params"]["requestId"],
'status': x["params"]["response"]["status"],
'statusText': x["params"]["response"]["statusText"]
}
)
補充
# 在再發過程中,我們需要固定版本的chrome瀏覽器,但是chrome會自動升級為最新版本,這時我們就需要更換對應版本的chrome驅動才能讓程序正常運行.
# 如何限制
1.打開一個chrome窗口,在地址欄輸入 : chrome://version/ 如圖一
2.復制個人資料路徑 C:\Users\pc\AppData\Local\Google 注意到Google結束
3.打開這個路徑 如圖二
4.如果沒有Update 這個文件夾就新建一個名為Update的文件夾
5.把Update文件夾權限限制掉
6.限制權限后點擊訪問該文件夾顯示沒有權限為設置成功
7.查看是否限制成功 chrome://settings/help 輸入這個地址 如果如圖三的顯示效果表示限制自動升級成功





聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角
【推薦】一下。您的鼓勵是博主的最大動力!
自 勉:生活,需要追求;夢想,需要堅持;生命,需要珍惜;但人生的路上,更需要堅強。
帶着感恩的心啟程,學會愛,愛父母,愛自己,愛朋友,愛他人。