selenium操作

原文:

https://www.cnblogs.com/Ting-light/p/9770908.html

官方文档:

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': '[email protected]|1535423998|0|blog|00&99|US&1535350140&blog#hub&420100#10#0#0|&0|blog|[email protected]', '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被展示

猜你喜欢

转载自blog.csdn.net/qq_41955893/article/details/86524595