zl程序教程

您现在的位置是:首页 >  工具

当前栏目

selenium源码通读·3 | 从源码看引入webdriver包的原因

源码 原因 引入 selenium WebDriver 通读
2023-06-13 09:16:56 时间

1 先看实例

  • 需求是:打开百度,输入NoamaNelson进行搜索
  • 代码实现:
# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/5/12
# 文件名称:selen_stu.py
# 作用:打开百度输入NoamaNelson
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

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

driver.find_element_by_id("kw").send_keys("NoamaNelson")
time.sleep(1)
driver.find_element_by_id("kw").send_keys(Keys.ENTER)
driver.maximize_window()
time.sleep(0.5)
driver.quit()

2 提出疑问

  • 为什么需要引入from selenium import webdriver包?
  • 为什么是webdriver.Chrome()
  • 带着这两个问题,我们来分析下

3 为什么引入webdriver包?

  • 因为webdriver中定义各种浏览器的支持
    在这里插入图片描述
  • 再看源码路径:Python37\Lib\site-packages\selenium\webdriver\__init__.py
from .firefox.webdriver import WebDriver as Firefox  # noqa
from .firefox.firefox_profile import FirefoxProfile  # noqa
from .firefox.options import Options as FirefoxOptions  # noqa
from .chrome.webdriver import WebDriver as Chrome  # noqa
from .chrome.options import Options as ChromeOptions  # noqa
from .ie.webdriver import WebDriver as Ie  # noqa
from .ie.options import Options as IeOptions  # noqa
from .edge.webdriver import WebDriver as Edge  # noqa
from .opera.webdriver import WebDriver as Opera  # noqa
from .safari.webdriver import WebDriver as Safari  # noqa
from .blackberry.webdriver import WebDriver as BlackBerry  # noqa
from .phantomjs.webdriver import WebDriver as PhantomJS  # noqa
from .android.webdriver import WebDriver as Android  # noqa
from .webkitgtk.webdriver import WebDriver as WebKitGTK # noqa
from .webkitgtk.options import Options as WebKitGTKOptions # noqa
from .remote.webdriver import WebDriver as Remote  # noqa
from .common.desired_capabilities import DesiredCapabilities  # noqa
from .common.action_chains import ActionChains  # noqa
from .common.touch_actions import TouchActions  # noqa
from .common.proxy import Proxy  # noqa
  • 可以看出,如果想支持某个浏览器,就需要selenium\webdriver\浏览器\webdriver
  • __init__.py中将对应的浏览器的webdriver进行了as方法引用

4 为什么是webdriver.Chrome()?

  • 从第三步的分析,我们如果想支持chrome浏览器,源码是
from .chrome.webdriver import WebDriver as Chrome  # noqa
  • 那么直接使用:webdriver.Chrome()即可

5 浏览器支持类型

  • 如果想支持其他浏览器,即:
driver = webdriver.Ie()      # ie支持
driver = webdriver.Firefox() # Firefox支持
driver = webdriver.Edge()    # Edge支持
# 等等
android:android浏览器支持
blackberry:blackberry平台支持
chrome:谷歌浏览器支持
edge:微软edge浏览器支持,一般要windows10及以上
firefox:火狐浏览器支持
ie:ie浏览器支持
opera:opera浏览器支持
phantomjs:内存模式可以渲染解析js、css、html,可以快速运行
safari:apple下的浏览器支持
webkitgtk:WebKitGTK是KDE、Apple、Google等公司共同开发的一套开源的Web浏览器引擎