Python selenium webdriver 的常用示例

系列文章目录

selenium webdriver 的常用示例

文章目录

  • 系列文章目录
  • selenium webdriver 的常用示例
  • 前言
  • 一、Pip安装&创建Bowser对象
  • 1.Pip install selenium
  • 2.创建Bowser对象
  • 二、webdriver.ChromeOptions配置
  • 配置浏览器的常用模式
  • 三、常用代码
  • 四、selenium的异常处理
  • 总结
  • 前言

    本文就介绍了Selenium的常用内容:了解Selenium Webdriver 是干什么的


    以下是本篇文章正文内容,下面案例可供参考

    一、Pip安装&创建Bowser对象

    1.Pip install selenium

    pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

    2.创建Bowser对象

    # 导入webdriver模块
    from selenium import webdriver
    
    # 指定使用Chrome浏览器
    driver = webdriver.Chrome()  # chrome_options,executable_path常用这两个参数
    

    二、webdriver.ChromeOptions配置

    配置浏览器的常用模式

    chromeoptions 的常用功能
    (1)添加启动参数 (add_argument)
    (2)添加扩展应用参数 (add_extension, add_encoded_extension),常用在代理身份验证
    (3)添加实验性质参数 (add_experimental_option)
    代码如下(示例):

    options= webdriver.ChromeOptions()  # 创建配置对象
    options.add_argument('lang=zh_CN.UTF-8')  # 设置中文
    options.add_argument('--headless')  # 无头参数,浏览器隐藏在后台运行
    options.add_argument('--disable-gpu') # 禁用GPU加速
    options.add_argument('--start-maximized')#浏览器最大化
    options.add_argument('--window-size=1280x1024') # 设置浏览器分辨率(窗口大小)
    options.add_argument('--user-agent=""') # 设置请求头的User-Agent
    options.add_argument('--incognito')  # 隐身模式(无痕模式)
    options.add_argument(f'--proxy-server={proxy}')  # 添加IP代理 proxy=f"http://{ip}:{port}"
    # 关闭'Chrome目前受到自動測試軟體控制'的提示
    options.add_experimental_option('useAutomationExtension', False)
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    prefs = {
    	"download.default_directory":"D:\download",  # 设置浏览器下载地址(绝对路径)
    	"profile.managed_default_content_settings.images": 2,  # 不加载图片
    }
    chrome_options.add_experimental_option('prefs', prefs)  # 添加prefs 
    # chrome_options="浏览器配置参数", executable_path="浏览器驱动绝对路径"
    driver = webdriver.Chrome(chrome_options=options")  # 创建浏览器对象
    driver.maximize_window()  # 浏览器窗口最大化
    driver.set_page_load_timeout(30)  # 设置连接超时30秒
    

    三、常用代码

    	# 导入webdriver模块
    	from selenium import webdriver
    	driver = webdriver.Chrome()  # chrome_options,executable_path常用这两个参数
    	# get 会一直等到页面被完全加载,然后才会执行下一步代码,如果超出了set_page_load_timeout()的设置,则会抛出异常。
    	driver.get("https://baidu.com/")
    	new_window = driver.window_handles[-1]   # 新窗口'-1'代表打开的最后一个窗口,导航栏有多少个窗口根据下标来锁定
    	driver.switch_to.window(new_window)  # 切换到新窗口:
    	driver.switch_to.frame('passport_iframe')  # 根据name或id 定位至 iframe
    	driver.switch_to.default_content()  # 切换出(iframe)至默认,有好多种切换方式找BaiDu
    	driver.find_element_by_xpath('//input[@xx="xxxx"]').send_keys(content)  # 根据xpath语法定位元素输入内容
    	driver.find_element_by_xpath('//div[@xx="xxxx"]').click()  # 根据xpath语法定位元素后并点击
    	driver.find_element_by_xpath('//div[@xx="xxxx"]').text  # 根据xpath语法定位后获取元素的文本信息
    	driver.get_cookie('name')  #根据name取出对应字典类型的对象
    	driver.get_cookies()  # 返回一个列表,包含多个字典类型的对象
    	# 添加Cookie部分参数介绍:name=cookie的名称,value=cookie对应的值,domain=服务器域名,expiry=Cookie有效终止日期
    	driver.add_cookie({'name' : 'xxx', 'value' : 'xxx'})  # 添加cookie
    	driver.delete_cookie('name')  # 删除指定部分的Cookie
    	driver.delete_all_cookies()  # 删除所有Cookie
    	js="var q=document.documentElement.scrollTop=10000"  # 滚动到最下面
    	js="var q=document.documentElement.scrollTop=0"  # 滚动到最上面
    	driver.execute_script(js)  # 执行JS代码,更多自行BaiDu 
    	driver.quit()  # 退出浏览器
    

    四、selenium的异常处理

    # 导入exceptions模块
    from selenium.common import exceptions
    try:
    	# 执行代码 
    except exceptions.TimeoutException:
    	print("xxxx - 请求加载超时异常!\n", end='')
    except exceptions.NoSuchElementException:
       	print("xxxx - 网页元素定位异常!\n", end='')
    except exceptions.NoSuchWindowException:
    	print("xxxx - 目标窗口切换异常!\n", end='')
    except exceptions.WebDriverException:
       	print("xxxx - 浏览器对象各种异常!\n", end='')
    except Exception:
    	print("xxxx - 以上未捕捉到的异常!\n", end='')
    

    selenium 更多异常参考:https://blog.csdn.net/cunhui1209/article/details/112544287


    总结

    例如:以上就是今天要记录的内容,本文仅仅简单介绍了selenium的使用,selenium 提供了大量能使我们捷地实现自动化测试的函数和方法,后续会在本文的基础上记录新的常用操作。
    Google官方下载地址:https://www.google.cn/chrome/
    Google驱动下载地址:https://npm.taobao.org/mirrors/chromedriver/
    驱动配置请参考:https://blog.csdn.net/flyskymood/article/details/123203105

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python selenium webdriver 的常用示例

    发表评论