• selenium基础用法


    快速入门

    调用环境变量指定的PhantomJS浏览器创建浏览器对象

    from selenium import webdriver
    driver = webdriver.Chrome(executable_path=r"C:Program Files (x86)GoogleChromeApplicationchromedriver.exe")
    

    get方法会一直等到页面被完全加载,然后才会继续程序,通常测试会在这里选择 time.sleep(2)

    driver.get('https://www.baidu.com/')
    

    获取页面名为 wrapper的id标签的文本内容

    data = driver.find_element_by_id('wrapper').text
    
    data
    
    '新闻
    hao123
    地图
    视频
    贴吧
    学术
    登录
    设置
    更多产品
    下载百度APP
    有事搜一搜  没事看一看
    把百度设为主页关于百度About  Baidu百度推广
    ©2019 Baidu 使用百度前必读 意见反馈 京ICP证030173号  京公网安备11000002000001号 '
    

    打印页面标题 "百度一下,你就知道"

    driver.title
    
    '百度一下,你就知道'
    

    生成当前页面快照并保存

    driver.save_screenshot('baid.png')
    
    True
    
    driver.save_screenshot('baid.png')
    
    True
    

    id="kw"是百度搜索输入框,输入字符串"马云"

    driver.find_element_by_id('kw').send_keys('马云')
    

    id="su"是百度搜索按钮,click() 是模拟点击

    driver.find_element_by_id('su').click()
    

    获取新的页面快照

    driver.save_screenshot('马云.png')
    
    True
    

    打印网页渲染后的源代码

    driver.page_source
    
    '<html><head>
        
        <meta http-equiv="content-type" content="text/html;charset=utf-8"><style data-for="result" id="css_result" type="text/css">body{color:#333;background:#fff;padding:6px 0 0;margin:0;position:relative;min-900px}body,th,td,.p1,.p2{font-family:arial}p,form,ol,ul,li,dl,dt,dd,h3{margin:0;padding:0;list-style:none}input{padding-top:0;padding-bottom:0;-moz-box-sizing:border-box;-webkit-box-sizing:b
    .....
    

    获取当前页面Cookie

    driver.get_cookies()
    
    [{'domain': 'www.baidu.com',
      'httpOnly': False,
      ....
    

    要想调用键盘按键操作需要引入keys包

    from selenium.webdriver.common.keys import Keys
    

    ctrl+a 全选输入框内容

    driver.find_element_by_id('kw').send_keys(Keys.CONTROL,'a')
    

    ctrl+x 剪切输入框内容

    driver.find_element_by_id('kw').send_keys(Keys.CONTROL,'x')
    

    输入框重新输入内容

    driver.find_element_by_id('kw').send_keys('王健林')
    
    driver.find_element_by_id('su').send_keys(Keys.RETURN)
    

    清除输入框内容

    driver.find_element_by_id('kw').clear()
    

    生成新的页面快照

    driver.save_screenshot('王健林.png')
    
    True
    

    获取当前url

    driver.current_url
    
    'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E7%8E%8B%E5%81%A5%E6%9E%97&oq=%25E9%25A9%25AC%25E4%25BA%2591&rsv_pq=91f8d64b0000e74c&rsv_t=baa2FFFF1WZYWQhU5LpuRXBg92yxLF4VBoGGv3MDbXE3Rs7uYv9kYjjnNxQ&rqlang=cn&rsv_enter=0&rsv_dl=tb&inputT=49232&rsv_sug3=5&bs=%E9%A9%AC%E4%BA%91'
    

    关闭当前页面,如果只有一个页面,会关闭浏览器

    driver.close()

    关闭浏览器

    driver.quit()
    

    页面操作

    Selenium 的 WebDriver提供了各种方法来寻找元素,假设下面有一个表单输入框:

    我们对上面的操作有

    <input type="text" name="user-name" id="passwd-id" />
    

    获取id标签值

    element = driver.find_element_by_id('pwsswd_id')
    

    获取name标签值

    element = driver.find_element_by_name('username')
    

    获取签名值

    element = driver.find_elements_by_tag_name('input')
    

    通过XPath匹配

    element = driver.find_element_by_xpath('//input[@id='passwd-id']')
    

    定义UI元素

    对于元素的选取,有如下的API单个元素选取

    find_element_by_id
    find_elements_by_name
    find_elements_by_xpath
    find_elements_by_link_text
    find_elements_by_partial_link_text
    find_elements_by_tag_name
    find_elements_by_class_name
    find_elements_by_css_selector

    By ID

    <div id="coolestWidgetEvah">...</div>
    
    ...
    element = driver.find_element_by_id("coolestWidgetEvah")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    element = driver.find_element(by=By.ID, value="coolestWidgetEvah")
    

    By Class Name

    <div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>
    
    Cheddar
    Gouda
    cheeses = driver.find_elements_by_class_name("cheese")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    cheeses = driver.find_elements(By.CLASS_NAME, "cheese")
    

    By Tag Name

    <iframe src="..."></iframe>
    
    frame = driver.find_element_by_tag_name("iframe")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    frame = driver.find_element(By.TAG_NAME, "iframe")
    

    By Name

    <input name="cheese" type="text"/>
    
    cheese = driver.find_element_by_name("cheese")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    cheese = driver.find_element(By.NAME, "cheese")
    
    <a href="http://www.google.com/search?q=cheese">cheese</a>
    

    cheese

    cheese = driver.find_element_by_link_text("cheese")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    cheese = driver.find_element(By.LINK_TEXT, "cheese")
    
    <a href="http://www.google.com/search?q=cheese">search for cheese</a>>
    

    search for cheese>

    cheese = driver.find_element_by_partial_link_text("cheese")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    cheese = driver.find_element(By.PARTIAL_LINK_TEXT, "cheese")
    

    By CSS

    <div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
    
    milkcheese
    cheese = driver.find_element_by_css_selector("#food span.dairy.aged")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    cheese = driver.find_element(By.CSS_SELECTOR, "#food span.dairy.aged")
    

    By XPath

    <input type="text" name="example" />
    <INPUT type="text" name="other" />
    
    inputs = driver.find_elements_by_xpath("//input")
    ------------------------ or -------------------------
    from selenium.webdriver.common.by import By
    inputs = driver.find_elements(By.XPATH, "//input")
    

    鼠标动作链

    1566731524447

    有些时候,我们需要再页面上模拟一些鼠标操作,比如双击、右击、拖拽甚至按住不动等,我们可以通过导入 ActionChains 类来做到:

    导入 ActionChains 类

    from selenium.webdriver import ActionChains
    
    from selenium import webdriver
    driver = webdriver.Chrome(executable_path=r"C:Program Files (x86)GoogleChromeApplicationchromedriver.exe")
    driver.get('https://www.baidu.com/')
    

    鼠标移动到 ac 位置

    ac = driver.find_element_by_xpath('element')
    ActionChains(driver).move_to_element(ac).perform()
    

    点击

    ac = driver.find_element_by_xpath("elementA")
    ActionChains(driver).move_to_element(ac).click(ac).perform()
    

    双击

    ac = driver.find_element_by_xpath("elementB")
    ActionChains(driver).move_to_element(ac).double_click(ac).perform()
    
    

    右击

    ac = driver.find_element_by_xpath("elementC")
    ActionChains(driver).move_to_element(ac).context_click(ac).perform()
    
    

    停住

    ac = driver.find_element_by_xpath('elementF')
    ActionChains(driver).move_to_element(ac).click_and_hold(ac).perform()
    

    将 ac1 拖拽到 ac2 位置

    ac1 = driver.find_element_by_xpath('elementD')
    ac2 = driver.find_element_by_xpath('elementE')
    ActionChains(driver).drag_and_drop(ac1, ac2).perform()
    

    填充表单

    <select id="status" class="form-control valid" onchange="" name="status">
        <option value=""></option>
        <option value="0">未审核</option>
        <option value="1">初审通过</option>
        <option value="2">复审通过</option>
        <option value="3">审核不通过</option>
    </select>
    
    # 导入 Select 类
    from selenium.webdriver.support.ui import Select
    
    # 找到 name 的选项卡
    select = Select(driver.find_element_by_name('status'))
    
    # 
    select.select_by_index(1)
    select.select_by_value("0")
    select.select_by_visible_text(u"未审核")
    

    1566731500008

    以上是三种选择下拉框的方式,它可以根据索引来选择,可以根据值来选择,可以根据文字来选择。注意:

    --index 索引从 0 开始
    --value是option标签的一个属性值,并不是显示在下拉框中的值
    --visible_text是在option标签文本的值,是显示在下拉框的值

    全部取消

    select.deselect_all()
    

    弹窗处理

    alert = driver.switch_to_alert()
    

    页面切换

    driver.switch_to.window("this is window name")
    

    for handle in driver.window_handles:
        driver.switch_to_window(handle)
    

    Cookies

    # 获取页面每个Cookies值,用法如下
    for cookie in driver.get_cookies():
        print "%s -> %s" % (cookie['name'], cookie['value'])
    
    # 删除Cookies,用法如下
    # By name
    driver.delete_cookie("CookieName")
    
    # all
    driver.delete_all_cookies()
    

    页面等待

    1566731484247

    注意:这是非常重要的一部分!!

    现在的网页越来越多采用了 Ajax 技术,这样程序便不能确定何时某个元素完全加载出来了。如果实际页面等待时间过长导致某个dom元素还没出来,但是你的代码直接使用了这个WebElement,那么就会抛出NullPointer的异常。

    为了避免这种元素定位困难而且会提高产生 ElementNotVisibleException 的概率。所以 Selenium 提供了两种等待方式,一种是隐式等待,一种是显式等待。

    隐式等待是等待特定的时间,显式等待是指定某一条件直到这个条件成立时继续执行。

    显式等待

    显式等待指定某个条件,然后设置最长等待时间。如果在这个时间还没有找到元素,那么便会抛出异常了。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    # WebDriverWait 库,负责循环等待
    from selenium.webdriver.support.ui import WebDriverWait
    # expected_conditions 类,负责条件出发
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome()
    driver.get("http://www.xxxxx.com/loading")
    try:
        # 页面一直循环,直到 id="myDynamicElement" 出现
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "myDynamicElement"))
        )
    finally:
        driver.quit()
    

    1566731470363

    如果不写参数,程序默认会 0.5s 调用一次来查看元素是否已经生成,如果本来元素就是存在的,那么会立即返回。

    下面是一些内置的等待条件,你可以直接调用这些条件,而不用自己写某些等待条件了。

    title_is
    title_contains
    presence_of_element_located
    visibility_of_element_located
    visibility_of
    presence_of_all_elements_located
    text_to_be_present_in_element
    text_to_be_present_in_element_value
    frame_to_be_available_and_switch_to_it
    invisibility_of_element_located
    element_to_be_clickable – it is Displayed and Enabled.
    staleness_of
    element_to_be_selected
    element_located_to_be_selected
    element_selection_state_to_be
    element_located_selection_state_to_be
    alert_is_present
    

    隐式等待

    隐式等待比较简单,就是简单地设置一个等待时间,单位为秒。

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.implicitly_wait(10) # seconds
    driver.get("http://www.xxxxx.com/loading")
    myDynamicElement = driver.find_element_by_id("myDynamicElement")
    
  • 相关阅读:
    C# Process.Start()方法详解 .
    任务管理器
    20160113 js中选择多个check一块删除
    20160113 JS中CheckBox如何控制全选
    20151217JS便签
    20151216Repeater
    20151215单选按钮列表,复选框列表:CheckBoxList
    20151214下拉列表:DropDownList
    !!!SqlHelper 传智!
    !!! SQL 数据库开发基础 传智!
  • 原文地址:https://www.cnblogs.com/marklijian/p/11408932.html
Copyright © 2020-2023  润新知