selenium学习(三)

selenium find_element_by_定位方式语法改变,提示find_element_by_ commands are deprecated 上周重装系统升级了python版本从3.6升级到了3.8,发现旧的脚本不能用了,显示如下 提示: find_element_by_* commands are deprecated. Please use find_element() instead 看了下 为啥之前的方法不能用了,如下 def find_element_by_id(self, id_) -> WebElement: """Finds an element by id. :Args: 阅读详情

本节继续进行selenium源码学习,上一节介绍了浏览器对应得模块,本节记录公共模块

目录

一、remote目录

1.remote_connection.py

2.webdriver.py

(1)元素相关

(2)窗口相关 

(3) 截图相关

(4) cookie相关

3.switch_to.py 

4.webelement.py 

二、common目录

1.alert.py

2.action_chains.py

3.By.py 

 4.Key.py

三、support目录

 1.abstract_event_listener.py

2.color.py

3.expected_conditions.py

(1)title相关

(2)url相关

(3)元素相关

4.wait.py


一、remote目录

1.remote_connection.py

这个模块主要包含其他浏览器remote模块继承类RemoteConnection

包含一个全局类变量_timeout,用于标记链接超时时间,使用得是python socket库中全局默认超时时间

_timeout = socket._GLOBAL_DEFAULT_TIMEOUT

关于这个类全局变量包含四个函数,其中函数中得cls表示Class,与self不同,self参数需要创建类对象后方可使用,cls则表示类本身,所以可以不用创建对象直接调用

    @classmethod
    def get_timeout(cls):
        """
        :Returns:
            Timeout value in seconds for all http requests made to the Remote Connection
        """
        return None if cls._timeout == socket._GLOBAL_DEFAULT_TIMEOUT else cls._timeout

    @classmethod
    def set_timeout(cls, timeout):
        """
        Override the default timeout

        :Args:
            - timeout - timeout value for http requests in seconds
        """
        cls._timeout = timeout

    @classmethod
    def reset_timeout(cls):
        """
        Reset the http request timeout to socket._GLOBAL_DEFAULT_TIMEOUT
        """
        cls._timeout = socket._GLOBAL_DEFAULT_TIMEOUT

    @classmethod
    def get_remote_connection_headers(cls, parsed_url, keep_alive=False):
        """
        Get headers for remote request.

        :Args:
         - parsed_url - The parsed url
         - keep_alive (Boolean) - Is this a keep-alive connection (default: False)
        """

        system = platform.system().lower()
        if system == "darwin":
            system = "mac"

        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
            'User-Agent': 'selenium/{} (python {})'.format(__version__, system)
        }

        if parsed_url.username:
            base64string = base64.b64encode('{0.username}:{0.password}'.format(parsed_url).encode())
            headers.update({
                'Authorization': 'Basic {}'.format(base64string.decode())
            })

        if keep_alive:
            headers.update({
                'Connection': 'keep-alive'
            })

        return headers

2.webdriver.py

包含WebDriver类也就是其他浏览器所继承的模块,对于该类的参数以及初始化讲解在selenium学习(二)中以及提到过,就不详细介绍了,主要介绍有哪些函数

(1)元素相关

首先就是搜索元素的方法,也就是八种类型对应每个类型两种的方法,一个返回一个,一个返回列表

    def find_element_by_id(self, id_):
        return self.find_element(by=By.ID, value=id_)

    def find_elements_by_id(self, id_):
        return self.find_elements(by=By.ID, value=id_)

(2)窗口相关 

窗口相关的操作有尺寸、多窗口切换、刷新、前进后退等

例如:

# 执行当前窗口刷新操作,等于左上角刷新/F5
driver.refresh()
# 执行当前窗口的前进/后退操作,等于左上角的前进/后退
driver.forward()
driver.back()
# 执行窗口的切换,本质调用的都是driver.switch_to(),且用的是switch_to.py模块,后续介绍
driver.switch_to_alret()
driver.switch_to_window()
# 获取当前web对象包含的windows列表
driver.window_handles()
此时就可以通过连用,例如:
# 切换到第0个窗口
lists = driver.window_handles()
driver.switch_to_window(lists[0])
# 还有获取尺寸、放大、缩小等操作
driver.maximize_window()
driver.minimize_window()
driver.get_window_size(lists[0])
driver.set_window_size('111', '111')

(3) 截图相关

# 截图当前页面,并保存,save_screenshot本质调用的也是get_screenshot_as_file
driver.get_screenshot_as_file(filename)
driver.save_screenshot()
# 截图当前页面,并且转化为ascii
driver.get_screenshot_as_png()
driver.get_screenshot_as_base64()

(4) cookie相关

# 获取所有的cookie或者指定的cookie
driver.get_cookies()
driver.get_cookie(name)
# 添加对应的cookie
driver.add_cookie(cookie_dict)
# 删除所有cookie或者指定cookie
driver.delete_all_cookies()
driver.delete_cookie(name)

3.switch_to.py 

包含SwitchTo类,主要作用是切换浏览器下的各个窗口

    @property
    def alert(self):
        alert = Alert(self._driver)
        alert.text
        return alert

    def default_content(self):
        self._driver.execute(Command.SWITCH_TO_FRAME, {'id': None})

    def frame(self, frame_reference):
        if isinstance(frame_reference, basestring) and self._driver.w3c:
            try:
                frame_reference = self._driver.find_element(By.ID, frame_reference)
            except NoSuchElementException:
                try:
                    frame_reference = self._driver.find_element(By.NAME, frame_reference)
                except NoSuchElementException:
                    raise NoSuchFrameException(frame_reference)

        self._driver.execute(Command.SWITCH_TO_FRAME, {'id': frame_reference})

    def parent_frame(self):
        self._driver.execute(Command.SWITCH_TO_PARENT_FRAME)

    def window(self, window_name):
        if self._driver.w3c:
            self._w3c_window(window_name)
            return
        data = {'name': window_name}
        self._driver.execute(Command.SWITCH_TO_WINDOW, data)

4.webelement.py 

当你获取到一个元素时返回的就是WebElement这个对象,主要对这个对象进行一系列的操作获取爬取对应的类型,介绍常用的

# 进行元素点击
element.click()
# 判断元素是否被选中,主要用于复选框/勾选框等
element.is_selected()
# 判断元素是否启用
element.is_enabled()
# 返回元素的li tag列表,一般常用于ul下的li遍历,同样也包含八种16个函数
element.find_elements_by_tag_name('li')
# 对元素进行输入操作,一般用户input标签
element.send_keys('input')
# 获取元素的属性一般有以下两种方法
# 区别在于get_attribute一般用于获取编写html时输入的属性
# get_property一般用于获取编写html加载时DOM树生成的属性
# 不过目前基本大部分都是交合的,所以都可以使用
element.get_property('input')
element.get_attribute('input')

二、common目录

介绍部分常用模块

1.alert.py

Alert模块,控制浏览器的弹窗,初始化只需传入web对象

常用的有一个text属性,获取弹窗信息

    @property
    def text(self):
        """
        Gets the text of the Alert.
        """
        if self.driver.w3c:
            return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"]
        else:
            return self.driver.execute(Command.GET_ALERT_TEXT)["value"]

还有弹窗的接受accept以及取消dismiss,如果有输入框的弹窗还有send_keys函数

    def accept(self):
        """
        Accepts the alert available.

        Usage::
        Alert(driver).accept() # Confirm a alert dialog.
        """
        if self.driver.w3c:
            self.driver.execute(Command.W3C_ACCEPT_ALERT)
        else:
            self.driver.execute(Command.ACCEPT_ALERT)

2.action_chains.py

包含类ActionChains主要用户实现元素的操作,初始化函数如下

    def __init__(self, driver):
        """
        Creates a new ActionChains.

        :Args:
         - driver: The WebDriver instance which performs user actions.
        """
        self._driver = driver
        self._actions = []
        if self._driver.w3c:
            self.w3c_actions = ActionBuilder(driver)

 perform函数表示执行所有的存储操作,后续举例时介绍

reset_actions函数则表示清空所有存储的操作

click函数表示执行点击

click_and_hold表示长按

等等各类鼠标操作,这里就不一一举例了,可以自行查看

例如:

ActionChains(driver).move_to_element(el).click().pause(1).send_keys('input').pause(1).perform()
# 表示先移动到el元素然后点击,等待一秒后输入input再等待一秒,这是存储的所有操作
# 最后添加perform()则进行存储释放,执行上述描述的步骤

3.By.py 

By类,主要用户元素爬取时对应的方法,也就是我们常说的八种爬取类型,使用时直接By.ID即可

class By(object):
    """
    Set of supported locator strategies.
    """

    ID = "id"
    XPATH = "xpath"
    LINK_TEXT = "link text"
    PARTIAL_LINK_TEXT = "partial link text"
    NAME = "name"
    TAG_NAME = "tag name"
    CLASS_NAME = "class name"
    CSS_SELECTOR = "css selector"

 4.Key.py

Key类,主要存放键盘特殊的输入,使用时直接调用即可

class Keys(object):
    """
    Set of special keys codes.
    """

    NULL = '\ue000'
    CANCEL = '\ue001'  # ^break
    HELP = '\ue002'
    BACKSPACE = '\ue003'
    BACK_SPACE = BACKSPACE

例如:

ActionChains(driver).move_to_element(el).send_keys(By.ENTER).perform()
# 表示先移动到el元素然后输入回车

三、support目录

介绍部分常用模块

 1.abstract_event_listener.py

该模块只包含一个类AbstractEventListener,主要用于事件侦听器,但是类中所有得方法均未实现,所以需要进行继承后挑选需要得部分进行实现

class AbstractEventListener(object):
    """
    Event listener must subclass and implement this fully or partially
    """

    def before_navigate_to(self, url, driver):
        pass

    def after_navigate_to(self, url, driver):
        pass

    def before_navigate_back(self, driver):
        pass

    def after_navigate_back(self, driver):
        pass

2.color.py

该模块下包含一个Color类、匹配各类颜色字符得正则以及一个Colors字典,存储常用得颜色类型

用于显示颜色。输入一定得可解析得文本,例如‘#00ff33’/rgb(0, 255, 51)/'blue'

正则匹配分为RGB/RGBA/HEX/HEX3/HSL/HSLA

RGB_PATTERN = r"^\s*rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)\s*$"
RGB_PCT_PATTERN = r"^\s*rgb\(\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*\)\s*$"
RGBA_PATTERN = r"^\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
RGBA_PCT_PATTERN = r"^\s*rgba\(\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(\d{1,3}|\d{1,2}\.\d+)%\s*,\s*(0|1|0\.\d+)\s*\)\s*$"
HEX_PATTERN = r"#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})"
HEX3_PATTERN = r"#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])"
HSL_PATTERN = r"^\s*hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)\s*$"
HSLA_PATTERN = r"^\s*hsla\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*(0|1|0\.\d+)\s*\)\s*$"

Color类中,初始化一般接受四个函数,r,g,b,a

    def __init__(self, red, green, blue, alpha=1):
        self.red = int(red)
        self.green = int(green)
        self.blue = int(blue)
        self.alpha = "1" if float(alpha) == 1 else str(float(alpha) or 0)

主要使用得是静态form_string(str_)方法(匹配得过长,可自行前往源码查看)

@staticmethod
def from_string(str_):
   import re

   class Matcher(object):
        def __init__(self):
           self.match_obj = None

        def match(self, pattern, str_):
           self.match_obj = re.match(pattern, str_)
           return self.match_obj

        @property
        def groups(self):
           return () if self.match_obj is None else self.match_obj.groups()

     m = Matcher()

例如:调用Color.from_string("rgba(11, 22, 33, 0.1)").rgba,此时开始执行匹配机制

执行上面列出来得所有匹配,当匹配返回不为空时再执行对应返回,返回得均为Color得对象

        if m.match(RGB_PATTERN, str_):
            return Color(*m.groups)
        elif m.match(RGB_PCT_PATTERN, str_):
            rgb = tuple([float(each) / 100 * 255 for each in m.groups])
            return Color(*rgb)
        elif m.match(RGBA_PATTERN, str_):
            return Color(*m.groups)
        elif m.match(RGBA_PCT_PATTERN, str_):
            rgba = tuple([float(each) / 100 * 255 for each in m.groups[:3]] + [m.groups[3]])
            return Color(*rgba)
        elif m.match(HEX_PATTERN, str_):
            rgb = tuple([int(each, 16) for each in m.groups])
            return Color(*rgb)
        elif m.match(HEX3_PATTERN, str_):
            rgb = tuple([int(each * 2, 16) for each in m.groups])
            return Color(*rgb)
        elif m.match(HSL_PATTERN, str_) or m.match(HSLA_PATTERN, str_):
            return Color._from_hsl(*m.groups)
        elif str_.upper() in Colors.keys():
            return Colors[str_.upper()]
        else:
            raise ValueError("Could not convert %s into color" % str_)

此时后缀.rgba则表示该对象得rgba属性,包含如下三种

@property
def rgb(self):
    return "rgb(%d, %d, %d)" % (self.red, self.green, self.blue)

@property
def rgba(self):
    return "rgba(%d, %d, %d, %s)" % (self.red, self.green, self.blue, self.alpha)

@property
def hex(self):
    return "#%02x%02x%02x" % (self.red, self.green, self.blue)

最后会打印如下

from selenium.webdriver.support.color import Color
print(Color.from_string("rgba(11, 22, 33, 0.1)").rgba)

>rgba(11, 22, 33, 0.1)

3.expected_conditions.py

该模块主要用于判断,例如元素是否可点击,页面标题是否为需求字符等等类型

(1)title相关

title_is用于判断当前页面得title,也就是html中head里面得title,返回self.title == driver.title

例如:

import selenium
from selenium.webdriver.support import expected_conditions
web_driver = selenium.webdriver.Chrome()
web_driver.get("https://mp.csdn.net/")
print(expected_conditions.title_is('首页-CSDN博客')(web_driver))

>True

类似还有一个title_contains,不过返回的是self.title in driver.title

(2)url相关

url_to_be用于判断当前页面得url是否与输入得一致,返回self.url == driver.current_url

url_changes则与之相反,判断是否是不一致

url_matches则匹配浏览器得url中是否包含输入得正则,返回match is not None

url_contains则判断是否包含输入字符

例如:

import selenium
from selenium.webdriver.support import expected_conditions
web_driver = selenium.webdriver.Chrome()
web_driver.get("https://mp.csdn.net/")
print(expected_conditions.url_to_be("https://mp.csdn.net/")(web_driver))

# 这里是False是因为CSDN没有登录得情况下会默认跳转到登陆页面,所以url不为输入得
>False

(3)元素相关

剩余就不一一举例了,与元素相关得如果找到元素就返回元素,否则就返回false

    """
    方法	描述
    title_is(‘百度一下’)	判断当前页面的 title 是否等于预期
    title_contains(‘百度’)	判断当前页面的 title 是否包含预期字符串
    presence_of_element_located(locator)	判断元素是否被加到了 dom 树里,并不代表该元素一定可见
    visibility_of_element_located(locator)	判断元素是否可见,可见代表元素非隐藏,并且元素的宽和高都不等于0
    text_to_be_present_in_element_attribute(locator,attribute,text)
    visibility_of(element)	跟上一个方法作用相同,但传入参数为 element
    text_to_be_present_in_element(locator , ‘百度’)	判断元素中的 text 是否包含了预期的字符串
    text_to_be_present_in_element_value(locator , ‘某值’)	判断元素中的 value 属性是否包含了预期的字符串
    frame_to_be_available_and_switch_to_it(locator)	判断该 frame 是否可以 switch 进去,True 则 switch 进去,反之 False
    invisibility_of_element_located(locator)	判断元素中是否不存在于 dom 树或不可见
    element_to_be_clickable(locator)	判断元素中是否可见并且是可点击的
    staleness_of(element)	等待元素从 dom 树中移除
    element_to_be_selected(element)	判断元素是否被选中,一般用在下拉列表
    element_selection_state_to_be(element, True)	判断元素的选中状态是否符合预期,参数 element,第二个参数为 True/False
    element_located_selection_state_to_be(locator, True)	跟上一个方法作用相同,但传入参数为 locator
    alert_is_present()	判断页面上是否存在 alert
    """

4.wait.py

包含WebDriverWait类,主要用于web操作的等待判断,包含两个函数until以及until_not,一个表示内容是否存在,一个表示内容是否不存在初始化函数如下,接受参数

driver:操控的web对象

timeout:等待时间

poll_frequency:轮询间隔时间,默认为0.5

ignored_exceptions:忽略的错误类型,接受类型为元组,碰到该错误时提示为Timeout错误,也就是超时未检测到,

默认忽略NoSuchElementException

    def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
        self._driver = driver
        self._timeout = timeout
        self._poll = poll_frequency
        # avoid the divide by zero
        if self._poll == 0:
            self._poll = POLL_FREQUENCY
        exceptions = list(IGNORED_EXCEPTIONS)
        if ignored_exceptions is not None:
            try:
                exceptions.extend(iter(ignored_exceptions))
            except TypeError:  # ignored_exceptions is not iterable
                exceptions.append(ignored_exceptions)
        self._ignored_exceptions = tuple(exceptions)

until函数

    def until(self, method, message=''):
        """Calls the method provided with the driver as an argument until the \
        return value is not False."""
        screen = None
        stacktrace = None

        end_time = time.time() + self._timeout
        while True:
            try:
                value = method(self._driver)
                if value:
                    return value
            except self._ignored_exceptions as exc:
                screen = getattr(exc, 'screen', None)
                stacktrace = getattr(exc, 'stacktrace', None)
            time.sleep(self._poll)
            if time.time() > end_time:
                break
        raise TimeoutException(message, screen, stacktrace)

举例:

WebDriverWait(driver, 20, 2).until(expected_conditions.alert_is_present())

表示在20s内每隔2s进行一次轮询,直到出现弹窗则结束,20s未出现弹窗则提示TimeoutException

【原创】Selenium学习系列之(三)—Selenium基本命令 先上一张图片,其中红色图框标记的部分,分别回答了上一篇文章最后引出的三个问题,猜一猜能对应上不。 附上一期问题: 问题1.Selenium提供了testsuite-testcase组织结构,一个testsuite可以包含多个testcase。 问题2.通过上面的例子我们会发现,有些是hardcode,如果登录的密码修改了,我还是要去修改testcase,或者如果server的IP修改了我还是 阅读详情

相关推荐

Selenium学习三——利用Python爬取网页表格数据并存到excel

利用Python爬取网页表格数据并存到excel 1、具体要求: 读取教务系统上自己的成绩单,并保存到本地的excel中 2、技术要求: 利用Selenium+Python获取网页,自动登陆并操作到成绩单页面 通过xlwt模块,将表格保存到本地excel (其中xlwt模块通过cmd打开命令框,输入pip install xlwt下载) 3、主要代码: #创

yxStory的博客 2万+

python3 selenium 事件监听

python3 selenium 事件监听 做UI层自动化代码运行起来抛出的各种异常让人捉急,在排查问题过程中debug模式的调试加日志信息是常用的手段。介绍一种一种方法能监听WebDriver的事件,可以在WebDriver事件发生前后做一些事情,利用这个特性可以完成很多东西,比如报错自动截图等。 from selenium import webdriver from selenium.webdriver.support.events import EventFiringWebDriver, Abstra

花小田的魔法屋 3630

USB摄像头开发实战:从参数配置到图像采集的完整流程(Python+OpenCV)

本文详细介绍了USB摄像头开发的完整流程,从参数配置到图像采集,使用Python和OpenCV实现。内容涵盖硬件原理、环境配置、参数调优及高级优化技巧,帮助开发者解决常见问题如分辨率设置、帧率控制和灯光频闪等,提升开发效率。

star的博客 246

Python Selenium Web自动化框架 官网学习笔记

+环境搭建 1,python3.6+pycharm 2,selenium(2.xx/3.xx版本) pip install selenium==2.48.0 pip list pip show selenium pip uninstall selenium 3,安装浏览器驱动(浏览器版本对应selenium版本) 1,Firefox...

一碗烈酒的博客 2184

【VeriStand】从零构建HIL测试平台:核心概念、硬件选型与实战配置指南

本文详细介绍了如何从零构建HIL测试平台,涵盖核心概念、硬件选型与实战配置指南。重点解析了VeriStand生态系统的优势,包括开箱即用特性、与LabVIEW的黄金搭档配合及Python支持。通过实战案例和硬件选型建议,帮助工程师高效搭建可靠的HIL测试平台,提升测试效率与安全性。

weixin_29250573的博客 334

Dify Rerank 模型配置全流程解析:从报错定位到代码实现

Dify Rerank 模型配置全流程解析:从报错定位到代码实现

engchina的专栏 4475

Selenium3 Python WebDriver API源码探析(2):Selenium包目录结构、模块功能概述

Selenium 包结构概述 Selenium 包结构如下: selenium ├─common └─webdriver ├─android ├─blackberry ├─chrome ├─common │ ├─actions │ └─html5 ├─edge ├─firefox ├─ie ├─opera ├─phantomjs ├─remote ├─safari ├─support

mighty13的专栏 3万+

AI编程工具选哪个更高效?开发者深度评测

无论是代码生成、错误修复,还是架构设计,AI都能提供强大的辅助能力。然而,市面上AI编程工具众多,如何选择最适合自己的?本文将从代码质量、响应速度、多语言支持、集成能力等多个维度,为你解析2025年最主流的几款AI编程工具,帮助你做出更高效的选择。根据2025年最新调研数据,全球超过85%的开发者正在使用AI编程工具辅助开发,相比2023年增长了近40%。合理利用AI,能让你的开发效率提升数倍,但真正的核心竞争力,仍然在于你的编程思维和解决问题的能力。:技术较强的开发者、重视数据隐私的企业。

1864

事件驱动如何理解?什么场景下适合用?Python如何实现一个事件监听器?

产品小姐姐给了阿巩这样的业务需求:游戏服务器希望在玩家升级或者达成某项成就时触发多种效果。比如玩家升级后,全属性将会提高,解锁新的系统,可以学习其他技能且开启新的战斗模式……可以看出,玩家升级后,所有挂钩的业务都要集中在一起,依次被处理。首先我们使用if 玩家升级再逐条添加业务功能代码是完全可以实现的,但是这样写出来的代码耦合度极高,往往是“牵一发而动全身”,一旦后续新业务加入,还要继续插入代码。 为达到解耦效果,引入了事件驱动模型:我们把“玩家升级”包装成一个事件,任何对这个事件感兴趣的“观察者”只需要

Snippers的博客 1068

Android音频学习(十四)——加载音频设备

loadHwModule 是 Android 音频系统的核心初始化函数,负责加载音频硬件抽象层(HAL)的模块实现。它建立 AudioPolicyService 与底层硬件的桥梁,将配置文件(audio_policy_config.xml)中的标签<module>定义转化为可操作的硬件对象,加载的是音频硬件模块(HAL实现),每个模块对应一种音频设备类型,以动态库的形式存在,负责与底层音频硬件交互。

miemie2014的博客 1741

智能车赛道识别:八邻域算法的实战解析与优化

本文深入解析了智能车赛道识别中八邻域算法的核心原理与实战优化。作为兼顾性能与稳定性的经典方案,该算法通过模拟探险家环顾八方的策略,能精准追踪弯道与直道边界。文章详细拆解了代码逻辑,并提供了边界平滑、异常处理及应对十字路口、环岛等复杂场景的关键优化策略,助力开发者提升智能车视觉系统的鲁棒性与实时性。

weixin_29228781的博客 267

Selenium学习(三) selenium IDE 命令

目录 官方API 命令分类 实例 官方API 英文版的https://www.seleniumhq.org/selenium-ide/docs/en/api/commands/ 命令分类 大类 小类 数量 命令列表 工具类 - 5 pause、set speed、run、echo、 debugger 交互操作 总数 35 - 窗口 4 close、select frame、select window、set w.

1762

【异常】Nacos 2.x 核心报错:Server check fail (gRPC 端口连不通) 排查指南 Server check fail, please check server xxx-

Nacos 2.x 的 gRPC 升级大幅提升了推送效率,但也对网络基础设施提出了更高要求。遇到。

奶爸的编程之路,也就一周冷个三天 375

Python selenium库学习使用实操三

国庆回来,接着搬砖,上回说到使用selenium进行自动登录和简单表单的自动填写,由于短时间内多次登录,触发了系统的图像验证码机制,不得不迫使我去学习下验证码识别了。以上就是文字验证码图像识别的简单操作。接着研究下拉选择框的使用。

xs_2012的专栏 1173

使用xlwings在Python中对Excel表格进行操作是非常方便的,可以实现自动化处理、批量数据处理等功能

使用xlwings在Python中对Excel表格进行操作是非常方便的,可以实现自动化处理、批量数据处理等功能。本篇文章主要介绍如何使用xlwings对Excel表格进行多行多列数据设置和操作,并给出相应的源代码。接着,我们可以对这个范围内的所有单元格进行操作,如设置字体颜色、填充颜色、对齐方式等。以上就是使用xlwings对Excel表格进行多行多列数据操作和设置字体颜色、填充色和对齐方式的全部内容。最后,我们可以将数据写入到单元格中,也可以从单元格中读取数据。在Excel中,可以通过。

BUG?不存在的! 718

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Selenium之学习杂记(三)

基于Python官网的简单实战通过Selenium访问Python官网通过JavaScript修改Python官网的标题在搜索框搜索获取latest news部分Selenium的等待 通过Selenium访问Python官网 代码如下: # 导入selenium库、time库 from selenium import webdriver import time # 启动浏览器,打开python官网 driver = webdriver.Chrome() driver.get("https://www.p

qq_35194427的博客 296

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Selenium3自动化学习(三)

学习笔记-Selenium[səˈliːniəm] -WebDriver API 元素等待 一:元素等待 WebDriver提供了显式和隐式等待。 (1)显式等待:等条件成立则执行,达到最大等待时间抛出超时异常(TimeoutException) from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait # 通过as关键字将expected...

漫步云端的博客 7874

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

selenium学习(三)

selenium 3大时间等待与3大窗口切换

ilovelyh的博客 434

Selenium Python 学习教程(三)

(三)selenium元素定位 虫师 创建于 4 个月 之前 最后更新时间 2018-11-03 selenium定位方法 Selenium提供了8种定位方式。 id name class name tag name link text partial link text xpath css selector 这8种定位方式在Python selenium中所对应的方法为: find_elemen...

qq_21825489的博客 267

selenium学习过程三

1. 记录测试过程中,所见 即是所得,selenium 的所有内部程序都是用Javascipt编写的。[Javascrīpt: 由Netscape Communications 和Sun Micorsystems公司共同开发的一种描述语言,与Java 的关系比较松散。Javascrīpt 能为Web页添加基本的联机应用程序和功能,但它不是一种真正的面向对象语言。它的工作特点是...

weixin_33785972的博客 96

selenium学习笔记(三)

有时候,需要确定某网页中包含了某特殊字符。但是这些字符,可能不仅仅只会以一种形式出现,而是会以不同形式出现。如 &lt;div id="id1"&gt; &lt;div class="class1"&gt;&lt;h1&gt;某某固定字符&lt;/h1&gt;&lt;/div&gt; &lt;/div&gt; 与 &lt;div id="id

yangyangrenren的专栏 337

Selenium学习(三)Selenium总是崩溃的解决办法

在使用selenium打开浏览器总是崩溃,最近查资料获得可行的解决办法: 1 import sys 2 from selenium import webdriver 3 4 p = __import__('selenium.webdriver.firefox.webdriver',fromlist=('WebDriver'))    ##### 5 url = ...

weixin_30667649的博客 1638

python+selenium学习记录三

1.鼠标事件  from selenium.webdriver import ActionChains   导入提供鼠标操作的ActionChains 类context_click( )   右击double_click( )    双击move_to_element( )   鼠标悬停drag_and_drop( )    拖动perform( )   执行行为    right_click=d...

qq_35757882的博客 191

selenium+java学习记录三(api)

1、打开地址 Driver.get() Driver.navigate.to() 2、操作浏览器API 刷新:Driver.navigate().refresh() Driver.navigate().forward() Driver.navigate().back() Driver.getTitle() 获取当前窗口的url:Driver.getCurrentUrl() 窗口最大化:Dri...

qq_26424611的专栏 189
上一篇: Postman获取token
下一篇: telnet控制windows
python蛀虫
博客等级 码龄7年 1粉丝 5原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值