python使用selenium控制浏览器

一、启动指定版本的浏览器

如果想启动指定版本的浏览器,只需要在实例化浏览器对象的时候,传入options参数指定浏览器程序地址即可。
但是如果想同时指定driver的位置,需要注意版本的不同,selenium 4.x和selenium 3.x版本指定的方式有所不同,两个版本具体的代码如下所示。

1.1 selenium 4.x 版本

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


chrome_options = Options()
chrome_options.binary_location = r'D:\chrome\chrome.exe'  # 指定chrome位置
chrome_service = Service(r'D:\chrome\chromedriver.exe')  # 指定chromedriver位置
driver = webdriver.Chrome(options=chrome_options, service=chrome_service)
driver.get('https://www.baidu.com')

1.2 selenium 3.x 版本

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


chrome_options = Options()
chrome_options.binary_location = r'D:\chrome\chrome.exe'  # 指定chrome位置
chrome_driver_path = r'D:\chrome\chromedriver.exe'  # 指定chromedriver位置
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=chrome_options)
driver.get('https://www.baidu.com')

需要注意的是:selenium 3.x版本需配合urllib 1.x版本使用。
在实际测试中,如果selenium 3.x与urllib 2.x搭配使用,在实例化Chrome对象的时候会报以下错误:

Exception has occurred: ValueError
Timeout value connect was <object object at 0x0000012D494B6050>, but it must be an int, float or None.
TypeError: float() argument must be a string or a number, not 'object'

During handling of the above exception, another exception occurred:

  File "D:\python\main.py", line 8, in <module>
    driver = webdriver.Chrome(executable_path=chrome_driver_path, options=chrome_options)
ValueError: Timeout value connect was <object object at 0x0000012D494B6050>, but it must be an int, float or None.

二、selenium常见使用方式

2.1 使用无头模式和声明屏幕大小

from selenium.webdriver import ChromeOptions

options = ChromeOptions()
options.add_argument('--headless')  # 无头模式
options.add_argument("--window-size=1200,800")  # 设置窗口大小
driver = webdriver.Chrome(options=options)

2.2 使用元素等待

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
try:
    WebDriverWait(driver, 10, 0.2).until(
        EC.presence_of_element_located((By.XPATH, '/html/frameset/frame[3]'))
    )
except Exception as reason:
    print('失败', reason)

2.3 切换frame

frame 和 iframe 使用下面的切换方式,其他 frame 按元素对待

# 切出到主文档
switch_to.default_content()
# 切换到frame,使用name或id
driver.switch_to.frame("menu")

2.4 保存屏幕截图

from PIL import Image
driver.save_screenshot(imgname)

三、操控手机浏览器

操控手机浏览器,要求电脑安装有adb(关于如何安装adb,可以参考使用adb删除手机内置软件),
同时要求手机安装有对应浏览器(比如Chrome),然后启用开发者选项,打开"USB调试"和"USB调试(安全设置)"选项,

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


chrome_options = Options()
chrome_options.enable_mobile()  # 操控手机浏览器
chrome_service = Service(r'D:\portable\chrome\chromedriver.exe')
driver = webdriver.Chrome(options=chrome_options, service=chrome_service)
driver.get('https://www.baidu.com')
posted @ 2020-07-05 09:51  那个白熊  阅读(308)  评论(0编辑  收藏  举报