1. 程式人生 > >python + selenium -- 讀取配置文件內容

python + selenium -- 讀取配置文件內容

mic erl fire python ref www Coding __main__ 文件路徑

任何一個項目,都涉及到了配置文件和管理和讀寫,python 支持很多配置文件的讀寫本文記錄使用 python + selenium自動化過程中,學習的使用python自帶的ConfigParser類讀取ini配置文件方法。

1、在所在項目新建一個文件夾,如config,在配置文件中新建一個文件,如config.ini

配置文件填寫內容如下:

1 [broswer_name]
2 broswer = firefox
3 
4 [server]
5 server = http://www.baidu.com/

2、使用系統自帶的os模塊獲取文件路徑

百度搜了很多的方式來獲取文件絕對路徑,如下方式最佳

1 os.path.abspath(os.path.join(config,config.ini))

3、編寫讀取配置文件的類,方便後續調用

# coding=utf-8
import ConfigParser
import os

class Config_read(object):
    def get_value(self):
        #file_path = os.path.dirname(os.path.realpath(__file__)) + os.path.join(r‘\config‘,‘config.ini‘)
        file_path = os.path.abspath(os.path.join(
config,config.ini)) config = ConfigParser.ConfigParser() config.read(file_path) #print file_path browser = config.get("broswer_name", "broswer") #分別代表所在區域名 和變量名 url = config.get("server", "server") return (browser, url) if __name__ == __main__: trcf
= Config_read() print trcf.get_value()

python + selenium -- 讀取配置文件內容