一、操作webdriver
webdriver元素定位方式
selenium.webdriver定位方式分为以下8类
- ID = ‘id’
- CLASS_NAME = ‘class name’
- NAME = ‘name’
- LINK_TEXT = ‘link text’
- PARTIAL_LINK_TEXT = ‘partial link text’
- TAG_NAME = ‘tag name’
- CSS_SELECTOR = ‘css selector’
- XPATH = ‘xpath’
Selenium实际提供了18种定位方式,详见下面表格
定位方式 | 解析 | 对应函数(单数) | 对应函数(负数) |
---|---|---|---|
id | 通过id属性定位元素 | driver.find_element_by_id() | driver.find_elements_by_id() |
class name | 通过标签的class属性定位元素 | driver.find_element_by_class_name() | driver.find_elements_by_class_name() |
name | 通过标签的name属性定位元素 | driver.find_element_by_name() | driver.find_elements_by_name() |
link text | 通过标签中的文本准确定位元素 | driver.find_element_by_link_text() | driver.find_elements_by_link_text() |
partial link text | 通过标签中的文本模糊匹配查找元素 | driver.find_element_by_partial_link_text() | driver.find_elements_by_partial_link_text() |
tag name | 通过标签名称定位元素(注:在一个页面中,标签一定会重复,所以不用这个来进行定位) | driver.find_element_by_tag_name() | driver.find_elements_by_tag_name() |
css selector | 通过css Selector定位元素 | driver.find_element_by_css_selector() | driver.find_elements_by_css_selector() |
xpath | 通过xpath定位元素 | driver.find_element_by_xpath() | driver.find_elements_by_xpath() |
底层函数 | 以上定位方式实际底层都是通过调用这两个函数 | driver.find_element() | driver.find_elements() |
我们通过find_element()或者find_elements()函数继续深入查看代码,会发现,最后是向remote server发送了一个http请求,然后对结果处理后,最终返回。
举例:
driver.find_element_by_id('i1')
driver.find_element_by_class_name('c1')
driver.find_element_by_name('username')
driver.find_element_by_link_text('登录')
driver.find_elements_by_partial_link_text('录')
driver.find_element_by_tag_name('input')
driver.find_element_by_css_selector('#i1')
driver.find_element_by_xpath('//*[@id="i1"]')
Cookie处理
cookies格式为列表,内部元素为单个cookie,以字典形式存储
[
{
"domain": "www.jd.com",
"expiry": 1588132512,
"httpOnly": false,
"name": "abc",
"path": "/",
"secure": false,
"value": "webp"
},
{
"domain": ".jd.com",
"expiry": 1572148512,
"httpOnly": false,
"name": "__abc",
"path": "/",
"secure": false,
"value": "aaa"
}
]
函数 | 解析 | 使用方法 |
---|---|---|
get_cookie(name) | Get a single cookie by name. Returns the cookie if found, None if not. 根据cookie的key获取cookie信息。 | driver.get_cookie(‘my_cookie’) |
get_cookies() | Returns a set of dictionaries, corresponding to cookies visible in the current session. 获取所有cookie信息 | driver.get_cookies() |
add_cookie(cookie_dict) | Adds a cookie to your current session. 添加cookie,严格按照格式添加,cookie的key为name,value为value | driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’, ‘secure’:True}) |
delete_cookie(name) | Deletes a single cookie with the given name. 根据cookie的key对应删除cookie | driver.delete_cookie(‘my_cookie’) |
delete_all_cookies() | Delete all cookies in the scope of the session. 删除会话内的所有cookie | driver.delete_all_cookies() |
窗口操作
函数 | 解析 | 使用方法 |
---|---|---|
maximize_window() | Maximizes the current window that webdriver is using. 放大当前窗口,不需要传参 | driver.maximize_window() |
minimize_window() | Invokes the window manager-specific ‘minimize’ operation. 最小化特定窗口 | |
get_window_size(windowHandle=‘current’) | Gets the width and height of the current window. 获取当前窗口的宽、高 | driver.get_window_size() |
set_window_size(width, height, windowHandle=‘current’) | Sets the width and height of the current window. (window.resizeTo) 通过像素设置当前窗口大小 | driver.set_window_size(800,600) |
get_window_position(windowHandle=‘current’) | Gets the x,y position of the current window. 获取当前窗口针对于Windows的位置的坐标x,y | driver.get_window_position() |
set_window_position(x, y, windowHandle=‘current’) | Sets the x,y position of the current window. (window.moveTo) 设置当前窗口针对Windows的位置,x,y | driver.set_window_position(0,0) |
fullscreen_window() | Invokes the window manager-specific ‘full screen’ operation | |
current_window_handle | Returns the handle of the current window. 返回当前操作的浏览器句柄 | driver.current_window_handle |
window_handles | Returns the handles of all windows within the current session. | driver.window_handles |
switch_to_window(window_name) | Deprecated use driver.switch_to.window 窗口切换到其他标签页 | driver.switch_to.window(new_handle) |
对当前页面截图
函数 | 解析 | 使用方法 |
---|---|---|
get_screenshot_as_png() | Gets the screenshot of the current window as a binary data. 获取当前页面的二进制图片数据,需要自己去写入文件 | driver.get_screenshot_as_png() |
get_screenshot_as_file(filename) | Saves a screenshot of the current window to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. as_png的上层封装,只需要传入图片名称自动写成图片 | driver.get_screenshot_as_file(‘/Screenshots/foo.png’) |
执行JS
函数 | 解析 | 使用方法 |
---|---|---|
execute_script(script, *args) | Synchronously Executes JavaScript in the current window/frame. 执行JavaScript语句 | js = "$(‘input[id=train_date]’).removeAttr(‘readonly’)" driver.execute_script(js)去除input框只读属性 js=window.scrollTo(100,400)通过js来操作滚动条 |
关闭与退出
函数 | 解析 | 使用方法 |
---|---|---|
close() | Closes the current window. 当开启多个时,关闭当前页面 | driver.close() |
quit() | Quits the driver and closes every associated window. 退出并关闭所有页面驱动 | driver.quit() |
在driver操作中,quit和close方法有什么区别?
close是关闭浏览器标签,quit是退出浏览器进程;
close:浏览器打开了好几个标签页,需要进程句柄切换,那么我们可以用close把不用的句柄关掉
quit:当我们结束测试时,可以把浏览器进程关掉。
其他
函数 | 解析 | 使用方法 |
---|---|---|
current_url | Gets the URL of the current page. 返回当前Url | driver.current_url |
name | Returns the name of the underlying browser for this instance. 返回tag标题 | name = driver.name |
page_source | Gets the source of the current page. 返回页面源码 | driver.page_source |
title | Returns the title of the current page. 获取浏览器名称 如:chrome | title = driver.title |
二、操作webdriver的WebElement
函数 | 解析 | 使用方法 |
---|---|---|
clear() | Clears the text if it’s a text entry element. 清除文本内容 | |
click() | Clicks the element. 鼠标左键点击操作 | |
get_attribute(name) | Gets the given attribute or property of the element. 根据标签属性名称,获取属性value | # Check if the “active” CSS class is applied to an element. is_active = “active” in target_element.get_attribute(“class”) |
get_property(name) | Gets the given property of the element. 通过属性名称获取属性 | text_length = target_element.get_property(“text_length”) |
is_displayed() | Whether the element is visible to a user. 返回元素是否可见 True or False | |
is_enabled() | Returns whether the element is enabled. | |
is_selected() | Returns whether the element is selected. Can be used to check if a checkbox or radio button is selected. 返回元素是否被选中 True or False | |
send_keys(*value) | Simulates typing into the element.模拟用户输入 Use this to send simple key events or to fill out form fields 向输入框输入字符串 This can also be used to set file inputs. 如果input的type为file类型 可以输入文件绝对路径上传文件 | 输入字符串 orm_textfield = driver.find_element_by_name(‘username’) form_textfield.send_keys(“admin”) 上传文件 file_input = driver.find_element_by_name(‘profilePic’) file_input.send_keys(“path/to/profilepic.gif”) |
submit() | Submits a form. 模仿回车按钮 提交数据 | |
value_of_css_property(property_name) | The value of a CSS property. | |
location | The location of the element in the renderable canvas. 获取当前元素的坐标 | |
screenshot_as_png | Gets the screenshot of the current element as a binary data. 获取当前元素的二进制图片数据,需要自己去写入文件 | element_png = element.screenshot_as_png |
screenshot(filename) | Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. 传入图片路径,自动生成元素的图片 element.screenshot(‘/Screenshots/foo.png’) | |
size | The size of the element. 获取当前标签的宽和高 | |
tag_name | This element’s tagName property. 返回标签元素的名字 | |
text | The text of the element. 获取元素的文本内容 |
三、常见异常
异常 | 解析 |
---|---|
NoSuchElementException | 没有找到元素 |
NoSuchFrameException | 没有找到iframe |
NoSuchWindowException | 没找到窗口句柄handle |
NoSuchAttributeException | 属性错误 |
NoAlertPresentException | 没找到alert弹出框 |
ElmentNotVisibleException | 元素不可见 |
ElementNotSelectableException | 元素没有被选中 |
TimeoutException | 查找元素超时 |
参考文章:
https://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.name
https://selenium-python.readthedocs.io/
https://seleniumhq.github.io/selenium/docs/api/py/api.html