selenium 常用操作


官方文檔:

https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to_frame

 

通常初始步驟  導入 webdriver, 通過下載的chromedriver打開瀏覽器

from selenium import webdriver

bs = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver')

打開網址

bs.get('https://baidu.com')

 

更改cookies              

d_cookies=bs.get_cookies()                                                                                                                   #獲取當前cookies
bs.delete_all_cookies()                                                                                                                          #刪除所有cookies然后再把登陸后的cookies放進去
wy_cookies=[{'path': '/', 'secure': False, 'domain': '.163.com', 'httpOnly': False, 'value': 'b8df58865bd86ee3f8b458e53c950e10', 'expiry': 2166070058.40818, 'name': '_ntes_nuid'}, {'path': '/', 'secure': False, 'domain': '.163.com', 'httpOnly': False, 'value': 'ezq0pFuDlR2oYBobCwYaAg==', 'expiry': 1566886046.242035, 'name': 'usertrack'},..., {'path': '/', 'secure': False, 'domain': '.163.com', 'httpOnly': False, 'value': 'tian_kong_hen_mei@163.com|1535423998|0|blog|00&99|US&1535350140&blog#hub&420100#10#0#0|&0|blog|tian_kong_hen_mei@163.com', 'expiry': 1566960000.336024, 'name': 'P_INFO'}]

for cok in wy_cookies:                                                                                                                              #加入目標cookies
    bs.add_cookie(cok)
bs.refresh()                                                                                                                                              #刷新頁面

查找元素

selenium.webdriver.common.by.By 

CLASS_NAME='class name'元素class屬性值     CSS_SELECTOR='css selector' css選擇器        ID='id'元素id屬性值       LINK_TEXT='link text'元素文本值    

NAME='name'元素name屬性值     PARTIAL_LINK_TEXT='partial link text' 元素部分文本值    TAG_NAME='tag name'元素標簽值,如ul         XPATH='xpath'  xpath定位符

bs.find_element(By.XPATH,'//button[text()="Some text"]')

txt_list=bs.find_elements_by_css_selector('[class="nbw-bitm clearfix bdwb bds2 bdc0"]')                           # 通過css_selector查找
title=txt_list[0].find_element_by_xpath('.//h3[@class="btag title thide"]/a')                                               #在已查找的元素上通多xpath的相對路徑查找
login_check=bs.find_element_by_id('input_captcha')

img_path=check_img.get_attribute("src")                                                                                              #獲取元素的屬性scr值

login_name.clear()                                                                                                                                   #對於input元素,清空

login_name.send_keys('sometext')                                                                                                          #對元素   輸入 鍵值 

login_key.click()                                                                                                                                       #對元素點擊

cont.text                                                                                                                                                  #返回元素中的所有文本

 

cont_iframe=bs.find_element_by_id('Editor_Edit_EditorBody_ifr')                                                      #定位 html頁中的iframe元素
bs.switch_to_frame(cont_iframe)                                                                                                            #轉到指定元素的iframe里,可查找里面的元素

bs.switch_to_frame("frameName")  通過frameName轉到該frame,也可以通過 索引 轉到該frame的子frame,用.號連接 ,bs.switch_to_frame("frameName.0.child")轉到名字為frameName的frame中的第一個名字為child的子frame

bs.switch_to_default_content()                                                                                                                #轉到默認的頁面,可用於退出iframe

alert=driver.switch_to_alert()                                                                                                                  #轉到當前打開的彈窗元素

bs.forward()                                                                                                                                             瀏覽器向前一個頁面

bs.back()                                                                                                                                                    瀏覽器后退一個頁面

bs.save_screenshot(file)                                                                                                                           #將瀏覽器截屏圖保存到file

left = img.location['x']
top = img.location['y']                                                                                                                                                                      #獲取元素的坐標,即元素的左上頂點的坐標

imgWidth = left + img.size['width']
imgHeight = top + img.size['height']                                                                                                                                                #獲取元素的右下頂點的坐標

填表單

from selenium.webdriver.support.ui import Select

select=Select(driver.find_element_by_name('name'))                                                                              選框元素

select.select_by_index(index)                                                                                                                   選擇對應索引項

select.select_by_visible_text("text")                                                                                                       選擇對應 文本 項

select.select_by_value(value)                                                                                                                    選擇value屬性值 對應的項

select.deselect_all()                                                                                                                                  將select中所有已選中的項 取消選擇

all_selected_options=select.all_selected_options                                                                                     返回 所有已被選擇的項的列表

options=select.options                                                                                                                               返回 所有選項 的列表

 

 

等待,直到元素出現   selenium.webdriver.support.wait.WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceprions=None)

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

WebDriverWait(browser, 50).until(EC.presence_of_element_located((By.ID, 'LoginForm_username')))                 明確的等待50秒,而不拋出異常,直到指定元素出現

 

driver  :  WebDriver 實例 (IE,Firefox,Chrome or Remote)

timeout : 超時的秒數

poll_frequency : 查找元素的間隔秒數,默認為0.5秒

ignored_exceptions : 當該方法被調用時被忽略的異常類,默認只包含 NoSuchElementException 

until(method,message='')   :調用這個driver有的某個方法,直到該方法的返回值不為 False

until_not(method,message='') :直到該方法的返回值為 Flase

例 :element=WebDriverWait(driver,10).until(lambda x:x.find_element_by_id("someId"))

is_disappeared=WebDriverWait(driver,30,1,(ElementNotVisibleException)).until_not(lambda x:x.find_element_by_id("someId").is_displayed())

 

ecpected conditions擁有的方法

title_is  ,title_contains  ,presence_of_element_located     ,  visibility_of_element_located , visibility_of   ,presence_of_all_elements_located   ,text_to_be_present_in_element  , 

text_to_be_present_in_element_value ,frame_to_be_available_and_switch_to_it ,invisibility_of_element_located ,element_to_be_clickable ,staleness_of ,element_to_be_selected ,

element_located_selection_state_to_be , alert_is_present 

 

模糊的等待 Implicit Waits  用於設置當webdriver  試圖查找元素時的等待時間,這個元素並不是立即可用。默認設置的隱式等待時間是0,一旦設置,將作用於WebDriver對象的整個生命周期

driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("http://somedomain/url_that_delays_loading") myDynamicElement = driver.find_element_by_id("myDynamicElement")

 

執行js腳本

 js='window.open("https://i.cnblogs.com/EditPosts.aspx?opt=1")'                                                                      #在新標簽頁中打開網址

bs.execute_script(js)

 

瀏覽器已打開的標簽頁的  句柄

bs.window_handles                                                                                                                                             #返回所有標簽頁的句柄列表

bs.switch_to_window(bs.window_handles[0])                                                                                                      #將窗口切換到句柄列表中的第一個標簽頁

bs.close()                                                                                                                                                             #關閉當前標簽頁           

bs.current_url                                                                                                                                                    #返回當前窗口的url 

browser.set_window_size(1720, 800)                                                                                                                 #設置瀏覽器窗口大小

基本異常類型

selenium.common.exceptions.WebDriverException

 

動作鏈 ActionChains             用於自動按順序執行一系列的動作,一般用於鼠標移動,點擊,鍵盤輸入 

from selenium.webdriver.common.action_chains import ActionChains 

sliper=check_line.find_element_by_xpath('./div/img')

news=driver.find_element_by_css_selector("a[title='新浪新聞']")

action=ActionChains(bs).move_to_element(sliper).click(news)      

action.perform()

也可寫作 actions=ActionChains(bs)          actions.move_to_element(sliper)            actions.click(news)     actions.perform()

動作會存儲在一個隊列中,當調用perform()時,動作被按順序執行,隊列被清空

ActionChains對象的方法

click(on_element=None)                                                                                                                              點擊 ,如果入參為None,則在當前位置點擊

click_and_hold(on_element=None)                                                                                                             在某元素上  按下鼠標左鍵,不松   

context_click(on_element=None)                                                                                                              選中某元素,鼠標右鍵    

double_click(on_element=None)                                                                                                                在某元素上雙擊

drag_and_drop(source,target)                                                                                                                  在source元素上按下鼠標左鍵,拖到元素target處釋放

drag_and_drop_by_offset(source,xoffset,yoffset)                                                                                 把元素source拖到相對位置(xoffset,yoffset)

key_down(value,element=None)                                                                                                                 在某元素上,按住某個鍵(僅用於調整鍵 Ctrl ,Alt,Shift)

 

ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() 執行ctrl+c

 

key_up(value,element=None)                                                                                                                     在某元素上,釋放某個鍵(僅用於調整鍵 Ctrl ,Alt,Shift)

move_by_offset(xoffset,yosffset)                                                                                                           讓鼠標移動相對位移(xoffset,yoffset)

move_to_element(to_elemnt)                                                                                                                    把鼠標移動到元素中心

move_to_element_with_offset(to_element,xoffset,yoffset)                                                                      通過一個相對位移,將鼠標移動到元素to_element , 坐標原點為左上頂點

pause(seconds)                                                                                                                                           暫停所有輸入    在特定的秒數期間

perform()                                                                                                                                                   執行所有存儲的動作

release(on_element=None)                                                                                                                        在某元素上釋放一個鼠標按鍵

reset_actions()                                                                                                                                          清除已存儲的動作

send_keys(*keys_to_send)                                                                                                                         在當前聚焦的元素上 輸入按鍵

send_keys_to_element(lelement,*keys_to_send)                                                                                      向某個元素輸入按鍵

 鍵值

Special Keys                                                                                                                                            鍵盤 ,鍵值

from selenium.webdriver.common.keys import Keys

elem.send_keys(Keys.RETURN)

elem.clear()                                                                                                                                              輸入內容前不會自動清空,可用clear()清空input中 已有內容

 

element.send_keys(" and some", Keys.ARROW_DOWN) 輸入 " and some ",然后按下 向下鍵

 Chrome WebDriver

class

selenium.webdriver.chrome.webdriver.WebDriver(executable_path='chromedriver',port=0,options=None,service_args=None,desired_capabilities=None,service_log_path=None,chrome_options=None)

Base:selenium.webdriver.remote.webdriver.WebDriver                                            ,chromedriver下載地址:http://chromedriver.storage.googleapis.com/index.html

 executable_path : 下載的chromedriver的路徑

port : 該服務運行的端口號,默認0表示自動選擇一個可用的端口號

desired_capabilities:dict類型,用於無頭瀏覽器特定存儲容器,例存儲proxy,loggingPref等

options:接收ChromeOptions實例

具有的方法:

create_options()

get_network_conditions()  獲取chrome 網絡競爭設置,返回一個dict,例如{‘latency':4,’download_throughput':2,'upload_throughput':2,'offline':False}

launch_app(id)   通過chrome應用的id啟動chrome應用

quit() 關閉瀏覽器並停止chromedirver

set_network_conditions(**network_conditions) 設置chrome網絡競爭設置 ,network_conditions:dict類型,

例如 driver.set_network_conditions(offline=False,latency=5, #額外的延遲(毫秒)

                 download_throughput=500*1024,#最大吞吐量

                 upload_throughput=500*1024)#最大吞吐量

‘throughput’可以同時設置上傳和下載的吞吐量

 

 

 

無頭瀏覽器phantomjs設置請求頭 

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

exe_path = 'E:\\Code\ayspider\\bin\\phantomjs.exe'

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap['phantomjs.page.settings.userAgent'] = (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
)
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
}
for key, value in headers.items():
   dcap['phantomjs.page.customHeaders.{}'.format(key)] = value

proxy = webdriver.Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = proxy_ip
proxy.add_to_capabilities(dcap)

browser = webdriver.PhantomJS(executable_path=exe_path,desired_capabilities=dcap)
browser.set_window_size(1720, 800) # 這里是關鍵,對於無頭瀏覽器,必須窗口設置,否則報錯
browser.get(url)

 

Remote WebDriver 

class selenium.webdriver.remote.webdriver.WebDriver(command_executor='http://127.0.0.1:4444/wd/hub',desired_capabilities=None,browser_profile=None,proxy=None,keep_alive=False,file_detector=None,options=None)

屬性: session_id .: 瀏覽器會話的 字符串id , 被這個webdriver控制的會話

capabilities : 這個瀏覽器會話返回的 字典形式的 有效容器,右這個remote server返回,詳見 https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities

command_executor .  :用於執行指令 remote_connection.RemoteConnection 對象

error_handler . :  errorhandler.ErrorHandler 對象 ,用於處理異常

 

desired_capabilities: 瀏覽器會話 發送請求時附加信息的dict形式容器

browser_profile   : 一個 selenium.webdriver.firefox.firefox_profile.FirefoxProfile 對象 ,僅用於火狐瀏覽器需要時

proxy :  selenium.webdriver.common.proxy.Proxy  對象 ,瀏覽器會話會通過設定的 代理 進行請求

file_detector  :  實例化過程的文件探測器,為None則啟用默認的 LocalFileDetector()

 方法:

add_cookie(cookie_dict) ,cookie_dict:dict類型,必要key ,"name","value";可選key:"path","domain",secure","expiry"   

使用方式例 driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’})           driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’})              driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’, ‘secure’:True})

 back() 瀏覽器歷史記錄后退一步

close() 關閉當前窗口

create_web_element(element_id) 用元素id創建web元素

delete_all_cookies()刪除session種的所有cookie ,driver.delete_all_cookies()

delete_cookie(name) ,根據name刪除指定cookie

execute(driver_command,params=None)在瀏覽器控制台執行的指令,driver_command:string, params:dict ,返回response的dict形式

execute_async_script(script,*args) 在當前窗口異步執行javascript。 script:執行的javascript腳本,args:script種需要的參數,

例:script = “var callback = arguments[arguments.length - 1]; ” “window.setTimeout(function(){ callback(‘timeout’) }, 3000);”                driver.execute_async_script(script)

execute_script(script,*args)  在當前窗口同步的執行javascript

file_detector_context(*args,**kwds):如果需要重置當前限制的環境下的文件探測器,確保原始的文件探測器被設置在其后

find_element(by='id',value=None)

forward() :在瀏覽器歷史中向前一步

fullscreen_window()  :使用窗口的”最大化“操作

get(url):在當前的瀏覽器會話中加載頁面

get_cookie(name) :根據name獲取cookie值

get_cookies() :返回當前會話中可見的cookies ,dict形式

get_log(log_type):返回給定類型的log ,例 driver.get_log(‘browser’)     driver.get_log(‘driver’)        driver.get_log(‘client’)           driver.get_log(‘server’)

get_screenshot_as_base64() :返回當前屏幕截圖的base64編碼字符 

get_screenshot_as_file(filename) :將當前屏幕截圖保存到全路徑filename

get_screenshot_as_png() :返回當前屏幕截圖的二進制數值

get_window_position(windowHandle='current') 返回當前窗口的位置(x,y)

get_window_rect() :返回當前窗口的坐標(x,y)和當前 ‘高’,‘寬’ 值

get_window_size(windwoHandle='current') :返回當前窗口的 寬,高 

implicitly_wait(time_to_wait) 

maximize_window():最大化當前窗口

minimize_window():調用窗口的 ‘最小化’ 操作

refresh()

save_screenshot(filename):保存當前瀏覽器截圖

set_page_load_timeout(time_to_wait):設置頁面加載的等待時間,超時則報錯

set_script_timeout(time_to_wait):設置異步執行腳本的等待時間,超時則報錯

set_window_position(x,y,windowHandle='current') :設置窗口的位置

set_window_rect(x=None,y=None,width=None,height=None) :設置窗口的位置和高寬    例,driver.set_window_rect(x=10, y=10)    driver.set_window_rect(width=100, height=200)    driver.set_window_rect(x=10, y=10, width=100, height=200)

set_window_size(width,height,windowHandle='current') :設置窗口的寬,高

start_client() :在開啟新會話前調用,可以通過覆寫該方法來定義個性化的 開啟行為

start_session(capabilities,browser_profile=None):用目標容器capabilities 來創建一個新會話 ,參數{browser_name:請求的瀏覽器名稱,version:請求的瀏覽器版本,platform:請求的瀏覽器所在的平台,javascript_endabled:新會話是否應該支持javascript, browser_profile :僅用於火花瀏覽器需要時

stop_client() :在執行quit()后調用的方法,可以通過覆寫該方法來個性化 關閉的行為

switch_to_active_element() :等同於 driver.switch_to.active_element

application_cache :返回ApplicationCache對象來與瀏覽器應用 緩存 交互

current_url :返回當前頁面的url

current_window_handle :返回當前窗口的句柄

desired_capabilities:返回drivers當前 被使用的 desired capabilities 

file_detector 

log_types :返回可用的log 類型列表

mobile

name:返回當前瀏覽器實例driver的name 

orientation :獲取當前設備的 環境狀態

page_source : 獲取當前頁的資源

switch_to : 例如  element = driver.switch_to.active_element                alert = driver.switch_to.alert              driver.switch_to.default_content()            driver.switch_to.frame(‘frame_name’)         

driver.switch_to.frame(1)       driver.switch_to.frame(driver.find_elements_by_tag_name(“iframe”)[0])          driver.switch_to.parent_frame()              driver.switch_to.window(‘main’)

title :返回當前頁的標題

window_handles : 返回當前會話的所有 窗口 handles 列表

預期狀態 

Expected conditions Support

class 

selenium.webdriver.support.expected_conditions.alert_is_present     預期有一個alert被展示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM