• selenium with python学习笔记


    1.环境配置

    • 安装Python并配置环境
    • 在cmd中键入pip install selenium,等待安装,如果安装成功键入pip show selenium
    • 安装Chrome浏览器,安装相应版本的driver(浏览器驱动)

    2.程序案例

     1 from selenium import webdriver
     2 from selenium.webdriver.common.keys import Keys
     3 import time
     4 
     5 driver = webdriver.Chrome() # 通过浏览器对应的驱动打开浏览器
     6 driver.get("http://www.baidu.com") # 在当前页面打开指定页面
     7 
     8 elem = driver.find_element_by_id("kw") # 通过id查找元素
     9 time.sleep(2) # 睡眠2秒
    10 elem.clear() # 清除文本
    11 elem.send_keys("百度百科")  # 键入字符串
    12 
    13 button = driver.find_element_by_id("su")
    14 button.click() # 点击元素
    打开百度,搜索百度百科
    • elem.clear(),用于清空输入框的文本,如果元素不是可编辑的,则会报以下异常selenium.common.exceptions.InvalidElementStateException: Message: invalid element state: Element must be user-editable in order to clear it.
    • time.sleep(s),用于程序休眠,单位是S
    • elem.clcik(),模拟点击函数,如果元素没有点击事件也不会报错.
     1 from selenium import webdriver
     2 from selenium.webdriver.common.keys import Keys
     3 import time
     4 
     5 
     6 def getHandle():
     7     return driver.current_window_handle # 获得驱动的浏览器窗口句柄
     8 
     9 
    10 driver = webdriver.Chrome()
    11 driver.get("http://www.baidu.com")
    12 print('打开第一个窗口',getHandle())
    13 
    14 js = "window.open('https://www.cnblogs.com/')" # 通过window对象打开一个页面
    15 driver.execute_script(js) # 执行JavaScript代码
    16 print('利用JS代开一个新窗口',getHandle())
    17 
    18 
    19 print('所有窗口句柄',driver.window_handles)
    20 # 当前的页面聚焦在第二个页面
    21 time.sleep(1)
    22 driver.switch_to.window(driver.window_handles[0])
    在窗口之间切换
    • driver.current_window_handle,返回驱动的window对象句柄(初始值是driver.get()的窗口句柄)
    • driver.execute_script(js),执行js代码
    • driver.window_handles,返回一个window句柄数组
    • driver.switch_to.window(handle),通过句柄切换窗口聚焦

     3.等待页面加载完成(Waits)

     1 from selenium import webdriver
     2 from selenium.webdriver.common.keys import Keys
     3 import time
     4 
     5 def getHandle():
     6     return driver.current_window_handle
     7 
     8 
     9 
    10 keys = "百度百科"
    11 driver = webdriver.Chrome() # 通过浏览器对应的驱动打开浏览器
    12 driver.implicitly_wait(10)
    13 driver.get("http://www.baidu.com") # 在当前页面打开指定页面
    14 elem = driver.find_element_by_id("kw") # 根据id查找
    15 elem.send_key("XXX")
    16 # 没有找到程序一直在等待
    17 print("没有找到等待10秒抛出异常")
    implicitly_wait()隐式等待
    • implicitly_wait(s),设置全局等待时间,默认是0.没有找到元素0秒后抛出异常
    1 from selenium import webdriver
    2 from selenium.webdriver.support.wait import WebDriverWait
    3 from selenium.webdriver.support import expected_conditions as EC
    4 
    5 driver = webdriver.Chrome()
    6 driver.get("http://www.baidu.com")
    7 WebDriverWait(driver,10).until(EC.title_is("百度一下,你就知道123"))
    8 # 可以尝试通过控制台更改title
    9 print("10秒内,每0.5秒执行一次")
    WebDriverWait().until()显示等待
    1 from selenium import webdriver
    2 from selenium.webdriver.support.wait import WebDriverWait
    3 from selenium.webdriver.support import expected_conditions as EC
    4 
    5 driver = webdriver.Chrome()
    6 driver.get("http://www.baidu.com")
    7 WebDriverWait(driver,10,5).until_not(EC.title_is("百度一下,你就知道123"),"没有找到")
    8 # 可以尝试通过控制台更改title
    9 print("10秒内,每5秒执行一次")
    WebDriverWait().until_not()显示等待
    • 模块:from selenium.webdriver.support.wait import WebDriverWait
    • WebDriverWait(driver,timeout,poll_frequency,ignored_exceptions).until(method,message)
    • WebDriverWait(driver,timeout,poll_frequency,ignored_exceptions).until_not(method,message)
    • driver: 传入WebDriver实例,即我们上例中的driver
      timeout: 超时时间,等待的最长时间
      poll_frequency: 调用until或until_not中的方法的间隔时间,默认是0.5秒
      ignored_exceptions: 忽略的异常,如果在调用until或until_not的过程中抛出这个元组中的异常,则不中断代码,继续等待,如果抛出的是这个元组外的异常,则中断代码,抛出异常。默认只有NoSuchElementExceptio
      method: 在等待期间,每隔一段时间调用这个传入的方法,直到返回值不是False
      message: 如果超时,抛出TimeoutException,将message传入异常
      参数
    • until 当某元素出现或什么条件成立则继续执行
    • until_not 当某元素消失或什么条件不成立则继续执行
    • 两个方法的method,必须是含有__call__的可执行方法。所以我们引用selenium提供的一个模块 from selenium.webdriver.support import expected_conditions as EC
    '''隐式等待和显示等待都存在时,超时时间取二者中较大的'''
    locator = (By.ID,'kw')
    driver.get(base_url)
     
    WebDriverWait(driver,10).until(EC.title_is("百度一下,你就知道"))
    '''判断title,返回布尔值'''
     
    WebDriverWait(driver,10).until(EC.title_contains("百度一下"))
    '''判断title,返回布尔值'''
     
    WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID,'kw')))
    '''判断某个元素是否被加到了dom树里,并不代表该元素一定可见,如果定位到就返回WebElement'''
     
    WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,'su')))
    '''判断某个元素是否被添加到了dom里并且可见,可见代表元素可显示且宽和高都大于0'''
     
    WebDriverWait(driver,10).until(EC.visibility_of(driver.find_element(by=By.ID,value='kw')))
    '''判断元素是否可见,如果可见就返回这个元素'''
     
    WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,'.mnav')))
    '''判断是否至少有1个元素存在于dom树中,如果定位到就返回列表'''
     
    WebDriverWait(driver,10).until(EC.visibility_of_any_elements_located((By.CSS_SELECTOR,'.mnav')))
    '''判断是否至少有一个元素在页面中可见,如果定位到就返回列表'''
     
    WebDriverWait(driver,10).until(EC.text_to_be_present_in_element((By.XPATH,"//*[@id='u1']/a[8]"),u'设置'))
    '''判断指定的元素中是否包含了预期的字符串,返回布尔值'''
     
    WebDriverWait(driver,10).until(EC.text_to_be_present_in_element_value((By.CSS_SELECTOR,'#su'),u'百度一下'))
    '''判断指定元素的属性值中是否包含了预期的字符串,返回布尔值'''
     
    #WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it(locator))
    '''判断该frame是否可以switch进去,如果可以的话,返回True并且switch进去,否则返回False'''
    #注意这里并没有一个frame可以切换进去
     
    WebDriverWait(driver,10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR,'#swfEveryCookieWrap')))
    '''判断某个元素在是否存在于dom或不可见,如果可见返回False,不可见返回这个元素'''
    #注意#swfEveryCookieWrap在此页面中是一个隐藏的元素
     
    WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='u1']/a[8]"))).click()
    '''判断某个元素中是否可见并且是enable的,代表可点击'''
    driver.find_element_by_xpath("//*[@id='wrapper']/div[6]/a[1]").click()
    #WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//*[@id='wrapper']/div[6]/a[1]"))).click()
     
    #WebDriverWait(driver,10).until(EC.staleness_of(driver.find_element(By.ID,'su')))
    '''等待某个元素从dom树中移除'''
    #这里没有找到合适的例子
     
    WebDriverWait(driver,10).until(EC.element_to_be_selected(driver.find_element(By.XPATH,"//*[@id='nr']/option[1]")))
    '''判断某个元素是否被选中了,一般用在下拉列表'''
     
    WebDriverWait(driver,10).until(EC.element_selection_state_to_be(driver.find_element(By.XPATH,"//*[@id='nr']/option[1]"),True))
    '''判断某个元素的选中状态是否符合预期'''
     
    WebDriverWait(driver,10).until(EC.element_located_selection_state_to_be((By.XPATH,"//*[@id='nr']/option[1]"),True))
    '''判断某个元素的选中状态是否符合预期'''
    driver.find_element_by_xpath(".//*[@id='gxszButton']/a[1]").click()
     
    instance = WebDriverWait(driver,10).until(EC.alert_is_present())
    '''判断页面上是否存在alert,如果有就切换到alert并返回alert的内容'''
    print instance.text
    instance.accept()
     
    driver.close()
    案例

    http://www.cnblogs.com/L-Test/p/9299226.html

    4.操作select

     1 from selenium import webdriver
     2 from selenium.webdriver.support.ui import Select
     3 import time
     4 driver = webdriver.Chrome()
     5 driver.get('http://sahitest.com/demo/selectTest.htm')
     6 select = Select(driver.find_element_by_id("s4Id"))
     7 select.select_by_index(1)
     8 time.sleep(1)
     9 select.select_by_value("o4val")
    10 time.sleep(3)
    11 
    12 options2 = select.all_selected_options
    13 print("查看已选选项")
    14 for selected in options2:
    15     print(selected.text)
    16 
    17 options = select.options
    18 print("查看所有选项")
    19 for allSelect in options:
    20     print(allSelect.text)
    21 
    22 select.deselect_all()
    操作下拉框
    • 模块:from selenium.webdriver.support.ui import Select
    • select = Select(driver.find_element_by_id("xxx")),获得一个slect对象
    • select.select_ , 选中下拉框
    • select.deselect_ , 取消选中
    • select.options , 获得options对象
    • options.text , 获得options选项的值
  • 相关阅读:
    docker映射端口无法访问
    Tomcat日志分析
    linux服务器性能测试
    mysql库表结构对比工具
    网络基础知识,不懂看这里
    Python之redis、mysql进程守护
    linux文件查找工具
    nginx解决跨域问题
    redis插入单个较大的键值
    linux系统安全巡检脚本
  • 原文地址:https://www.cnblogs.com/xiaoxu-xmy/p/9683018.html
Copyright © 2020-2023  润新知