架构
安装
1、python安装selenium
pip install selenium
2、还可以在pycharm里安装,Pycharm-Preferences-python interpreter-添加-搜索selenium-install
安装chromedriver
安装selenium后无法调起浏览器,这是因为没有安装浏览器的webdriver,应该先安装webdriver到项目中,才能通过selenium控制浏览器
Chromedriver各版本地址:Chromedriver
将获取的Chromedriver放在python项目下
测试
# 导入webdriver类
from selenium import webdriver
def test_browser():
# 调用浏览器驱动,获取浏览器句柄,若当前项目没有driver,则需指定地址
# browser = webdriver.Chrome('/Users/用户/PycharmProjects/pytestwork/chromedriver')
browser = webdriver.Chrome()
# 通过句柄访问浏览器
browser.get("www.baidu.com")
# 通过句柄控制页面元素
browser.find_element_by_id("kw").send("selenium")
browser.find_element_by_id("test").click()
导航与交互
测试用例改造,将一条完整的case放到一个class中。
chrome提供一个功能,打开检查工具,切换到console,$("CSS_SELECTOR")
利用css查找元素,比如:$(".title")
$x("xpath")
:利用xpath查找元素
$(".title").getBoundingClientRect() # 获取坐标
print(driver.page_source)
:调试,打印元素内容
元素定位方法
1、ID定位,通过HTML的ID值获取元素,两种方法
find_element_by_id('user_login')
find_element(By.ID, 'user_login')
2、name定位
find_element_by_name('commit')
find_element(By.NAME, 'commit')
3、class定位
find_element_by_class_name('filter')
find_element(By.CLASS_NAME, 'user_login')
4、tag定位
find_element_by_tag_name()
find_element(By.TAG_NAME, 'user_login')
5、link定位
find_element_by_link_text()
find_element(By.LINK_TEXT, '社区')
6、partial link定位
find_element_by_partial_link_text()
find_element(By.PARTIAL_LINK_TEXT, 'user_login')
7、XPath定位
find_element(By.XPATH, "//a[contains(@title,'20190728')]")
find_element_by_xpath("//a[@id='user_login']")
find_element_by_xpath("//a[@name='user_login']")
find_element_by_xpath("//a[@class='user_login']")
find_element_by_xpath("//*[@id='user_login']")
find_element_by_xpath("//a[@type='submit']")
find_element_by_xpath('//a[contains(text(), "问卷")]/a')
//表示当前页面某个目录下, a表示定位元素的标签名,[@id="user_login"]表示这个元素的id属性值,(@title,'20190728')表示这个元素的title属性值,如果不想指定标签名,则可以用星号(*)代替,元素的任意属性值都可以使用,只要它能唯一的标识一个元素。
- 层级与属性结合
如果一个元素本身没有可以唯一标识这个元素的属性值,那么我们可以找其上一级元素,或上上级元素。
find_element_by_xpath("//span[@class='class名称']/span/input") - 使用逻辑运算符
如果一个属性不能唯一区分一个元素,我们还可以使用逻辑运算符连接多个属性来查找元素
find_element_by_xpath("//input[@id='值' and @class='值']/span/input")
8、CSS选择器定位
find_element(By.CSS_SELECTOR, '.filter.nav.nav-pills .active')
find_element(By.CSS_SELECTOR, '.title [title*="先到先得')
find_element(By.CSS_SELECTOR, '.media-heading>span')
find_element(By.CSS_SELECTOR, 'a[href$="82"]')
find_element(By.CSS_SELECTOR, 'a:nth-child(2)') # a标签的第二个子元素
CSS | XPATH |
---|---|
.title a | //div/a |
[attribute*="subString"] | //*[contains(@attribute,"sub")] |
9、定位一组元素
获取标签名为a的所有元素,获取链接中包含12345的元素
hrefs = self.driver.find_elements(By.TAG_NAME, 'a')
for href in hrefs:
if href.get_attribute('title') == '先到先得':
input.click()
等待机制
分为显示等待、隐式等待、强制等待
- 隐式等待:服务端轮询查找,告诉webdriver每隔0.5秒去更新dom结构,查找一次需要的元素,直到找到该元素(找到元素则不再等待),否则就超时不再查找
self.driver.implicitly_wait(5)
- 显式等待:客户端轮询查找。使用场景与隐式等待不同,一般在某个元素可以被点击时使用
在设置时间内,等待后面的条件发生。如果超过设置时间未发生,则抛出异常。在等待期间,每隔一定时间(默认0.5秒),调用until或until_not里的方法,直到它返回True或False. - 强制等待:time.sleep().不建议、不稳定,网速差的会超过你的写死的等待时间,设置的大又会导致在网速好的时候,所有的用例都会被拖得很慢
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
try:
# 如果省略message=“”,则By.ID外面是两层()
element = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.ID, "myDynamicElement"))
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,“kw”), message="")
)
finally:
driver.quit()
- driver:浏览器驱动
- timeout:最长超时时间,默认以秒为单位
- poll_frequency:检测的间隔步长,默认为0.5s
- ignored_exceptions:超时后的抛出的异常信息,默认抛出NoSuchElementExeception异常。
一般与until()和until_not()方法结合使用:
# 调用该方法提供的驱动程序作为一个参数,直到返回值为True
WebDriverWait(driver, 10, 0.5).until(method, message=' ')
# 调用该方法提供的驱动程序作为一个参数,直到返回值为False
WebDriverWait(driver, 10, 0.5).until_not(method, message=' ')
- 用expected_conditions来完成对特定状态的等待(条件判断:元素状态)
方法 | 说明 |
---|---|
title_is | 判断当前页面的 title 是否完全等于(==)预期字符串,返回布尔值 |
title_contains | 判断当前页面的 title 是否包含预期字符串,返回布尔值 |
presence_of_element_located | 判断某个元素是否被加到了 dom 树里,并不代表该元素一定可见 |
visibility_of_element_located | 判断元素是否可见(可见代表元素非隐藏,并且元素宽和高都不等于 0) |
visibility_of | 同上一方法,只是上一方法参数为locator,这个方法参数是 定位后的元素 |
presence_of_all_elements_located | 判断是否至少有 1 个元素存在于 dom 树中。举例:如果页面上有 n 个元素的 class 都是’wp’,那么只要有 1 个元素存在,这个方法就返回 True |
text_to_be_present_in_element | 判断某个元素中的 text 是否 包含 了预期的字符串 |
text_to_be_present_in_element_value | 判断某个元素中的 value 属性是否包含 了预期的字符串 |
frame_to_be_available_and_switch_to_it | 判断该 frame 是否可以 switch进去,如果可以的话,返回 True 并且 switch 进去,否则返回 False |
invisibility_of_element_located | 判断某个元素中是否不存在于dom树或不可见 |
element_to_be_clickable | 判断某个元素中是否可见并且可点击 |
staleness_of | 等某个元素从 dom 树中移除,注意,这个方法也是返回 True或 False |
element_to_be_selected | 判断某个元素是否被选中了,一般用在下拉列表 |
element_selection_state_to_be | 判断某个元素的选中状态是否符合预期 |
element_located_selection_state_to_be | 跟上面的方法作用一样,只是上面的方法传入定位到的 element,而这个方法传入 locator |
alert_is_present | 判断页面上是否存在 alert |
点击输入滑动actions
- 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)
:发送某个键到指定元素
-
from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
- 填表单
- 遍历选项
element = driver.find_element_by_xpath("//select[@name='name']")
all_options =element.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("value"))
option.click()
- 使用Select方法
# 单选
select = Select(driver.find_element_by_name('name'))
select.select_by_index(index=1)
select.select_by_visible_text('text')
select.select_by_value(value="value")
# 选中/取消选中所有
select = driver.find_element_by_id("id]")
select.deselect_all()
多窗口处理
- 获取当前窗口
- 切换窗口
for w in self.driver.window_handles:
logging.info(w)
self.driver.switch_to.window(w)
logging.info(self.driver.title)
self.driver.switch_to.window(self.driver.window_handles[-1]). # 切换到最后一个句柄
# driver.switch_to.frame(0)
# driver.switch_to.frame("frameName")
driver.switch_to.window("windowname") # window名字或者句柄
driver.switch_to_default_content() # 从所有帧中移出并在页面上切换焦点。
# 一旦我们搬出,它将无法访问页面中框架内的元素。
driver.switch_to.frame() # 根据元素id或 index切换
driver.switch_to.default_content() # 切换到默认 frame
driver.switch_to.parent_frame() # 切换到父级 frame
# 先找到标签iframe,再切到该iframe中
self.driver.switch_to.frame(self.driver.find_element(By.TAG_NAME, "iframe"))
表单
属性
element = self.driver.find_element(By.CSS_SELECTOR, "#new_user > div.from-group.checkbox > label")
logging.info(element.is_displayed())
logging.info(element.id)
logging.info(element.tag_name)
logging.info(element.text)
logging.info(element.location)
logging.info(element.rect)
logging.info(element.size)
logging.info(element.get_attribute("for"))
进入已经打开的浏览器进程
ChromeOptions是chromedriver支持的浏览器启动选项。
windows
chrome.exe --remote-debuggung-port=9222
Mac
- chrome进程查找chrome路径:
ps -ef | grep -i Chrome
- chrome路径:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
- 加参数:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debuggung-port=9222
使用上面这个方法,需要把所有浏览器进程关掉,否则不起效果。
chrome_options = webdriver.ChromeOptions()
chrome_options.debugger_address = '127.0.0.1:9222'
self.driver = webdriver.Chrome(chrome_driver_path)
options常用属性及方法为:
- binary_location=‘‘:指定Chrome浏览器路径
- debuger_address=‘:指定调试路径
- headless: 无界面模式
- add_argument():添加启动参数
- add_extension:添加本地插件
- add_experimental_option:添加实验选项
- to_capablilities:将options转为标准的capablitiies格式
# 无界面模式
options.add_argument(‘headless‘)
# 指定用户客户端-模拟手机浏览
options.add_argument('user-agent=""')
# 禁用图片加载
options.add_argument(‘blink-settings=imagesEnabled=false‘)
# 隐身模式
options.add_argument(‘incognito‘)
# 自动打开开发者工具
options.add_argument("auto-open-devtools-for-tabs")
# 设置窗口尺寸,注意宽高之间使用逗号而不是x
options.add_argument(‘window-size=300,600‘)
# 设置窗口启动位置(左上角坐标)
options.add_argument(‘window-position=120,0‘)
# 禁用gpu渲染
options.add_argument(‘disable-gpu‘)
# 全屏启动
options.add_argument(‘start-fullscreen‘)
# 全屏启动,无地址栏
options.add_argument(‘kiosk‘)
# 启动时,不激活(前置)窗口
options.add_argument(‘no-startup-window‘)
文件上传
def test_upload_file(self):
self.driver.execute_script("arguments[0].click();",
self.driver.find_element(By.CSS_SELECTOR, '.js_upload_file_selector'))
self.driver.find_element(By.CSS_SELECTOR, "#js_upload_input").\
send_keys("/Users/xxx/PycharmProjects/pytestwork/test_selenium/养猪.jpg")
print(self.driver.page_source)
WebDriverWait(self.driver, 5).until(
expected_conditions.invisibility_of_element_located((By.CSS_SELECTOR, ".js_uploadProgress_cancel"))
)
self.driver.execute_script("arguments[0].click();", self.driver.find_element(By.CSS_SELECTOR, ".js_next"))
注入JS
按钮无法通过click()方法点击,可以通过注入js的方式点击
def click_by_js(self, locator):
self.driver.execute_script("arguments[0].click();",
self.driver.find_element(locator))
- execute_script:执行js
- return:可以返回js的返回结果
- execute_script:arguments传参,arguments[0]表示第一个参数,argument[1]表示第二个参数
多浏览器管理
- chrome,firefox,heafless等浏览器的自动化支持
- 传不同的参数来测试不同的浏览器,用来做浏览器兼容性测试
Base.py
:创建setup和teardown方法
def setup():
# 获取浏览器参数
browser = os.getenv("browser")
# 判断浏览器参数
if browser == 'firefox':
self.driver = webdriver.Firefox()
elif browser == "headless":
self.drover = webdriver.PhantomJS()
else:
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(5)
self.driver.maximize_window()
def teardown():
self.driver.quit()
执行测试用例,只需要传递参数,执行测试用例。
cookie登录
- 第一次登录一个域名,网站会在response header中加入set-cookie头
- browser会保存cookie和domain
- 再次发起对相同domain的请求的时候,browser会把domain对应的cookie以cookie头的格式发送给对应的domain
def test_cookie(self):
url = "https://work.weixin.qq.com/wework_admin/frame#contacts"
self.driver.get(url)
cookies = {
"name": "wwrtx.vst", "value": "",
"name": "wwrtx.d2st", "value": "",
"name": "wwrtx.sid", "value": "",
"name": "wwrtx.ltype", "value": "",
"name": "wwrtx.corpid", "value": "",
"name": "wwrtx.vid", "value": "",
}
for k,v in cookies.items():
self.driver.add_cookie({"name": k, "value": v})
self.driver.get(url)
参考资料
- 官网: https://www.selenium.dev/projects/
- 下载: https://www.selenium.dev/downloads/
- python基础库: https://pypi.org/project/selenium/
- Java基础库: https://github.com/SeleniumHQ/selenium/releases/download/selenium-3.141.59/selenium-java-3.141.59.zip
- GitHub官网: https://github.com/SeleniumHQ/selenium
- 火狐: https://github.com/mozilla/geckodriver
- selenium-python官方文档: https://selenium-python.readthedocs.io/getting-started.html