Python 操作selenium

429 阅读2分钟

这是我参与更文挑战的第20天,活动详情查看: 更文挑战

前言

Python借助selenium可以操作浏览器进行自动化测试工作,下面就介绍一下相关的方法。

安装 selenium

pip install -U selenium 注意代码文件名不能写成selenium,否则会报

ImportError: cannot import name 'webdriver' from partially initialized module 'selenium' (most likely due to a circular import)

安装chrome的Driver

需要安装驱动之后才能操作浏览器,我放到了D盘下 下载地址: chromedriver.chromium.org/ 需要提交

控制浏览器访问网页

from selenium import webdriver  # 启动浏览器需要用到
driver = webdriver.Chrome('D:/chromedriver.exe')  # Optional argument, if not specified will search path.
login_url = 'https://www.baidu.com'
driver.get(login_url)

访问页面上的元素

只用find_element_by_xpath 就行,其他的都没这个好使 在get之后再使用方法获取元素

driver.implicitly_wait(20)
driver.find_element_by_xpath("//input[@id='kw']").send_keys("临时营地")
driver.find_element_by_xpath("//input[@id='su']").click()

为了保证页面上的元素都已经加载成功了,等待20秒钟

访问延时加载的元素

有时候元素不是一下子就出来的,比如ajax请求后创建的列表元素 下面就是一个等待10秒之后才创建的P元素

<!doctype html>
<html>
<meta charset=utf-8>
<title>Race Condition Example</title>

<script>
    setTimeout(function () {
        var newElement = document.createElement("p");
        newElement.textContent = "Hello from JavaScript!";
        document.body.appendChild(newElement);
    }, 10000);
</script>
</html>

隐式等待

刚才介绍的

driver.implicitly_wait(20)

就是隐式等待,个人不建议这种写法,因为可能会等待更长时间。

显式等待

之前的等待20秒钟并不是十分的优雅,因为加载时间可能比20秒要少,下面介绍一种方法来查询这种后出现的元素

from selenium import webdriver  # 启动浏览器需要用到
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome('D:/chromedriver.exe')  # Optional argument, if not specified will search path.
login_url = 'file:///C:/Users/wlzcool/Desktop/a.html'
driver.get(login_url)
# el = driver.find_element_by_xpath("//p")
el = WebDriverWait(driver, 20).until(lambda d: d.find_element_by_xpath("//p"))
print(el.text)

el = WebDriverWait(driver, 20).until(lambda d: d.find_element_by_xpath("//p")) 这句话表示会等待至多20秒,直到这个p标签出现为止 跟之前的等待20秒相比代码能更快的执行下去。

注意

隐式等待和显式等待不要混用,两者一起用的话等待时间不一定是多少了。

alert上信息获取

<!doctype html>
<html>
<meta charset=utf-8>
<title>Race Condition Example</title>

<script>
    setTimeout(function () {
        var newElement = document.createElement("p");
        newElement.textContent = "Hello from JavaScript!";
        newElement.onclick=function(){alert("test alert text");}
        document.body.appendChild(newElement);
    }, 10000);
</script>
</html>

这里官方写的不是很详细, from selenium.webdriver.support import expected_conditions 这个没有写出来,结果expected_conditions .alert_is_present()找不到对应的类就起不来

from selenium import webdriver  # 启动浏览器需要用到
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions 
driver = webdriver.Chrome('D:/chromedriver.exe')  # Optional argument, if not specified will search path.
login_url = 'file:///C:/Users/wlzcool/Desktop/a.html'
driver.get(login_url)
# el = driver.find_element_by_xpath("//p")
el = WebDriverWait(driver, 20).until(lambda d: d.find_element_by_xpath("//p"))
el.click()
# Wait for the alert to be displayed and store it in a variable
alert = WebDriverWait(driver, 20).until(expected_conditions .alert_is_present())

# Store the alert text in a variable
text = alert.text
print(text)

参考: stackoverflow.com/questions/1…

alert

alert点击确认

alert.accept()

confirm

confirm取消按钮的点击方法

alert.dismiss()

实际操作中用处不是很大,现在很少有用官方的alert的了。

总结

人生苦短,我用 Python,在强大的Python帮助下,我们只需几行代码就实现我们的自动测试需求。