美文网首页
Web自动化测试-Selenium遇到的问题记录

Web自动化测试-Selenium遇到的问题记录

作者: 黑魔法 | 来源:发表于2020-05-31 22:37 被阅读0次

使用背景

最近使用selenium测试网站功能,我的环境是mac电脑、python版本是python2.7. selenium使用google的webdirver。这里记录在过程中遇到的两个问题。

1、select 选择options的问题。

2、input框上传附件失败的问题。

环境准备

1、webdriver 为google浏览器。注意需要选用与电脑中浏览器对应的版本。

查看本机电脑对应的版本:点击查看

google各版本的下载地址:点击下载

2、将webdirver 放入环境变量中。

image image image

一、解决select 选择options的问题


from selenium.webdriver.support.select import Select

class Test():

  def setup_method(self, method):

    self.driver = webdriver.Chrome()

    self.driver.implicitly_wait(10)

    self.vars = {}

  def teardown_method(self, method):

    self.driver.quit()

  def selectById(self, id_name, index=1):

    obj = self.driver.find_element(By.ID, id_name)

    time.sleep(0.5)

    Select(obj).select_by_index(index)

方法selectById 为封装好的select选择器。id_name为css中元素的id名称,index为select下options的索引,从1开始。time.sleep(0.5)是因为option是通过ajax动态获取的,所以需要等待一下网络请求成功。

image

二、文件上传的问题

需要先注入一段js代码防止点击后弹出文件窗口,然后将文件路径写入到input元素中。需要注意的是,我在mac上,提示只能用google chrome的webdriver才能上传文件,火狐不能支持。

image

示例代码如下:


self.driver.execute_script("""

    document.addEventListener('click', function(evt) {

      if (evt.target.type === 'file')

        evt.preventDefault();

    }, true)

    """)

self.driver.find_element(By.CSS_SELECTOR, ".btn:nth-child(2)").click()

file_path = u"/Users/vincent/Desktop/测试.docx"

self.driver.find_element(By.CSS_SELECTOR, "#jbox-content #uploadFile").send_keys(file_path)

self.driver.find_element(By.CSS_SELECTOR, "#jbox-content #btnImportSubmit").click()

总结

其实也算不上是自动化测试,只是为了替自己简化一些工作任务,大多数操作使用selenium IDE 插件录制然后稍微修改一下即可使用。

相关文章

网友评论

      本文标题:Web自动化测试-Selenium遇到的问题记录

      本文链接:https://www.haomeiwen.com/subject/jxrdzhtx.html