使用selenium进行自动化测试

selenium 支持多个客户端:ruby,Java,python。可以用来对网页进行全面测试,支持真实浏览器测试。

  • firefox
  • IE
  • chrome
  • safari

支持多操作系统:

  • Linux
  • windows
  • mac osx

安装:

sudo pip install selenium

测试:

1 #coding=utf-8
2 from selenium import webdriver
3 b = webdriver.Firefox()
4 b.get("http://www.baidu.com")
5 b.find_element_by_id("kw").send_keys("渗透")
6 b.find_element_by_id("su").click()

在新窗口里面打开一个链接

1 b= webdriver.Firefox()
2 a = b.find_element_by_tag_name('a')
3 b.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", a)

切换到新窗口

1 b.switch_to_window(b.window_handles[-1])    #切换到最后一个打开的窗口
2 b.close()    #关闭
3 b.switch_to_window(b.window_handles[0])    #回到第一个打开的窗口

获取a的源代码

a.get_attribute('outerHTML')

获取href

a.get_attribute("href")

弹出窗口的完整代码:

 1 #coding:utf-8
 2 from selenium import webdriver
 3 
 4 b = webdriver.Firefox()
 5 b.get("http://www.cpython.org")
 6 links = b.find_elements_by_tag_name("a")
 7 
 8 for l in links:
 9     n = b.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", l)
10     href = n.get_attribute('href')
11     if href.find('mailto:') > -1:
12         continue
13     n.click()
14     b.switch_to_window(b.window_handles[-1])
15     b.close()
16     b.switch_to_window(b.window_handles[0])
原文地址:https://www.cnblogs.com/goodhacker/p/3352473.html