记录下,在python中使用selenium操作浏览器碰到的一些问题,以及开发的一些功能,作为大家的参考,主要是多浏览器方面,

多浏览器操作,

碰到有个需求是这样的,他需要在录入完一个平台后,要在另外一个平台进行审批操作,再回过头来,继续后续的操作。
实现思路是,新建了一个全局字典,把所有浏览器的webdriver存到全局字典里面,需要指定浏览器操作时,再通过对应的key来取出。这里的key通过动态生成的方式,防止重复。代码如下,
生成key,

def driver_key_num(driver):
    """
    动态driver以全局字典形式输出,
    :param driver: driver,
    :return:字典的key,
    """
    global driver_num
    global driver_dict
    driver_num_key = "driver_key" + str(driver_num)
    now_num = driver_num
    driver_num += 1
    driver_dict[driver_num_key] = driver
    driver_key = list(driver_dict.keys())
    return driver_key[now_num]

通过key取出driver,如果没有输入key,则默认取当前最新的driver,

def driver_handle(browser_name):
    """
    切换当前浏览器driver,
    :param browser_name: driver的key,
    :return:driver,
    """
    if browser_name:
        return driver_dict[browser_name]
    else:
        global driver
        return driver
多浏览器选择,

这个不知道有简便办法没,我的方法是这种的,通过指定浏览器,指定本地浏览器路径,和驱动路径,来进行匹配,不选的话,都走默认路径。主要就搞了这三个主流的浏览器,像360其实走的就是chrome的内容,直接用chrome的driver就可以了。要注意一点的是,驱动和浏览器内核版本是有对应关系的,要注意看一下,大致代码如下(搞成三个函数其实有点丑,想合并成一个的。)

def browser_chrome(browser_path="", driver_path=""):
    """
    谷歌内核浏览器兼容,
    :param browser_path: 浏览器路径,
    :param driver_path: 驱动路径,
    :return: driver,
    """
    global driver
    if len(browser_path) > 0:
        options = ChromeOptions()
        options.binary_location = browser_path
    else:
        options = None
    if len(driver_path) == 0 :
        driver_path = "chromedriver"
    driver = webdriver.Chrome(executable_path=driver_path, options=options)
    return driver

def browser_ie(browser_path="", driver_path=""):
    """
    ie内核浏览器兼容,
    :param browser_path: 浏览器路径,
    :param driver_path: 驱动路径,
    :return: driver,
    """
    global driver
    if len(browser_path) > 0:
        options = IeOptions()
        options.binary_location = browser_path
    else:
        options = None
    if len(driver_path) == 0 :
        driver_path = "IEDriverServer.exe"
    driver = webdriver.Ie(executable_path=driver_path, options=options)  # 需要在设置-安全-四个区域中统一启用安全模式,
    return driver

def browser_firefox(browser_path="", driver_path=""):
    """
    火狐内核浏览器兼容,
    :param browser_path: 浏览器路径,
    :param driver_path: 驱动路径,
    :return: driver,
    """
    global driver
    if len(browser_path) > 0:
        options = FirefoxOptions()
        options.binary_location = browser_path
    else:
        options = None
    if len(driver_path) == 0 :
        driver_path = "geckodriver"
    driver = webdriver.Firefox(executable_path=driver_path, options=options)
    return driver

打开浏览代码如下,

browser_select = {
    "br360" : browser_chrome,
    "chrome" : browser_chrome,
    "firefox": browser_firefox,
    "ie": browser_ie
}
driver = browser_select[browser_type](path_selenium, chrome_driver)

另外可能frame切换这块会比较麻烦点,我是拼接的xpath,然后在xpath里面进行判断,调用switch_to.frame进行切换,操作完,再使用switch_to.default_content()切换回来。

其它如打开浏览器,切换frame,点击事件,抓取事件,关闭,刷新,前进,后退,加载,等待,选择下拉框,获取属性,输入信息,等等基本功能,都没有什么太大问题,顺利搞完了,