Python3 自动化测试网页Selenium+PhantomJS

Python3 自动化测试网页Selenium+PhantomJS


本文由 Luzhuo 编写,转发请保留该信息.
原文: https://blog.csdn.net/Rozol/article/details/79974692


以下代码以Python3.6.1为例
Less is more!

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2018/4/17'

'''
## 介绍
 - Selenium
     - Selenium 是 Web 自动化测试工具, 为网站自动化测试而开发
     - 可以按指定的命令自动操作
     - 可以运行在所有主流的浏览器上 (使用时需要安装浏览器)
     - 文档: http://selenium-python.readthedocs.io/index.html
     - pip install selenium
     - selenium-3.11.0
 - PhantomJS
     - PhantomJS 是一个基于Webkit的无界面浏览器, 他会自己处理JavaScript, Cookie
     - 下载: http://phantomjs.org/download.html
 - chrome
     - chrome 是Google公司的浏览器, 有界面
     - chromedriver与chrome的版本有对应关系(如: v2.37 : v64-66)
     - chromedriver下载地址: [淘宝代理下载](http://npm.taobao.org/mirrors/chromedriver/)
     - driver = webdriver.Chrome(executable_path="C:\DevelopSoftware\chromedriver\chromedriver.exe")
'''

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys  # 按键操作
from selenium.webdriver import ActionChains  # 鼠标操作
from selenium.webdriver.support.ui import Select  # 下拉框
from selenium.webdriver.support.ui import WebDriverWait  # 循环等待
from selenium.webdriver.support import expected_conditions as ec  # 条件出发

def demo():

    driver = webdriver.PhantomJS(executable_path=r"C:\DevelopSoftware\phantomjs-2.1.1-windows\bin\phantomjs.exe")
    driver.get("http://www.baidu.com")
    driver.implicitly_wait(1)

    elem = driver.find_element_by_class_name("s_ipt")
    elem.clear()
    elem.send_keys("luzhuo.me")
    elem.send_keys(Keys.RETURN)
    driver.implicitly_wait(5)

    driver.save_screenshot("baidu.png")
    driver.close()
    driver.quit()


def funcs():
    # 创建浏览器
    # driver = webdriver.PhantomJS()  # 需要配置环境变量
    driver = webdriver.PhantomJS(executable_path=r"C:\DevelopSoftware\phantomjs-2.1.1-windows\bin\phantomjs.exe")

    driver.get("http://www.baidu.com")

    # --- 获取 ---
    # 获取标签
    # tag = driver.find_element_by_id("kw")  # id
    tag = driver.find_element_by_class_name("s_ipt")  # class
    tag = driver.find_element_by_name("name")  # name
    tag = driver.find_elements_by_tag_name("div")  # tag
    tag = driver.find_element_by_xpath("//input[@id='input-id']")  # xpath匹配
    tag = driver.find_elements_by_link_text("登录")  # link; <a href="http://xxx">登录</a>
    tag = driver.find_elements_by_css_selector("p.content")  # css selector; <p class="content">XXX</p>

    # data = tag.text  # 获得标签的内容
    # title = driver.title  # 获取标题
    # data = driver.page_source  # 获取网页源码
    # data = driver.get_cookies()  # 获取cookie
    driver.delete_cookie("CookieName")  # 删除cookie
    driver.delete_all_cookies()
    driver.add_cookie({'name': 'foo', 'value': 'bar'})
    url = driver.current_url  # 获取当前url

    # driver.save_screenshot("baidu.png")  # 截图

    # --- 操作 ---
    # 键盘操作
    tag.send_keys(u"西红柿")  # 往标签发送内容, 中文字加u
    # tag.click()  # 点击标签
    # tag.clear()  # 清空内容
    tag.send_keys(Keys.CONTROL, 'a')  # Ctrl+A  # 按下组合键
    # tag.send_keys(Keys.SHIFT, 's')  # Shift+S
    tag.send_keys(Keys.RETURN)  # 回车
    # 鼠标操作
    ActionChains(driver).move_to_element(tag).perform()  # 移到指定标签处
    # 单击:click(tag) / 双击: double_click(tag) / 右击:context_click(tag) / 左键按住:click_and_hold(tag) / 拖拽:drag_and_drop(tag1, tag2)
    ActionChains(driver).move_to_element(tag).click(tag).perform()  # 单击该标签

    # 设置cookie
    driver.get("http://www.baidu.com")  # 要先请求下才能设置cookie, 否则unable to set cookie
    driver.add_cookie({"domain": "www.baidu.com",  # 域名(部分驱动不用填写)
                        'name': 'aaa',  # cookie名
                        'value': 'nonononnononono',  # cookie值
                        "expires": "",  # cookie有效期
                        'path': '/',  # 哪些路径使用
                        'httpOnly': False,
                        'HostOnly': False,
                        'Secure': False,})
    driver.get("http://www.baidu.com")

    # --- 表单操作 ---
    '''
    <select id="status">
        <option value=""></option>
        <option value="0">男</option>
        <option value="1">女</option>
    </select>
    '''
    select = Select(driver.find_element_by_id('status'))
    select.select_by_index(1)  # 选择第2个, 0开始
    select.select_by_value("0")  # 选择 value="0"
    select.select_by_visible_text(u"男")  # 选择 内容=男
    select.deselect_all()  # 取消选择


    # --- 弹框 ---
    alert = driver.switch_to_alert()
    alert.accept()  # 接收
    alert.dismiss()  # 关闭
    data = alert.text  # 内容
    alert.send_keys("text")  # 输入内容


    # --- 页面 ---
    driver.switch_to.window("window name")  # 切换页面
    handlers = driver.window_handles  # 获取窗口的handler
    driver.page_source.find('next')  # 搜索页面资源, 没有-1
    driver.forward()  # 前进
    driver.back()  # 后退
    # 隐式等待
    driver.implicitly_wait(10)  # 等待10s

    # 显示等待
    '''
    title_is(标题[是标题不是title属性]) / title_contains
    presence_of_element_located(某元素(如id="kw")是否存在) / presence_of_all_elements_located(返回列表)
    visibility_of_element_located(某元素是否可见) / visibility_of
    text_to_be_present_in_element(某元素是否有字符串) / text_to_be_present_in_element_value(属性中是否有字符串)
    frame_to_be_available_and_switch_to_it(是否是可选择的frame) / invisibility_of_element_located
    element_to_be_clickable(是否可点击) / 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
    '''
    element = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.ID, "idvalue"))  # 10秒内每0.5s查看页面是否出现 id="myDynamicElement"
        # ec.presence_of_element_located((By.XPATH, "//..."))
        # ec.presence_of_element_located(driver.find_element(By.XPATH, "//..."))
    )


    # --- 执行JS脚本 ---
    js = "$('.scroll_top').click(function(){$('html,body').animate({scrollTop: '0px'}, 800);});"  # 滚到底部
    js = "document.body.scrollTop=10000"  # 向下滚动10000px(差不多到底部)
    driver.execute_script(js)


    # 关闭页面
    driver.close()
    # 关闭浏览器
    driver.quit()



if __name__ == "__main__":
    demo()
    funcs()
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rozol/article/details/79974692
文章标签: Selenium PhantomJS
个人分类: Python
上一篇Python3 HTML数据解析(lxml/BeautifulSoup/JsonPath)
下一篇Python3 Scrapy爬虫框架(Scrapy/scrapy-redis)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭