python+selenium excel中文讀取填充到網頁

來源:互聯網
上載者:User

標籤:水平   error   exce   driver   code   try   val   return   cat   

由於我技術水平,磨磨唧唧很長時間終於弄出來了,在整理的時候思考了下,可能是我當時太關注列印出來的list了 ,list裡不能顯示中文,我就初以為我總是錯了。

附上表格一部分

 

#coding:utf-8import xlrddef open_excel(file):    try:        data = xlrd.open_workbook(file)        return data    except Exception as e:        print (str(e))def excel_table_byindex(file,colnameindex = 0,by_index= 0):    data = open_excel(file)    table = data.sheets()[by_index]    nrows = table.nrows    #行    colnames = table.row_values(colnameindex)    #列內容    list=[]    for rownum in range(1, nrows):        row = table.row_values(rownum)        if row:            app = {}            for i in range(len(colnames)):                s = row[i]
# if isinstance(s, unicode): # s = row[i].encode("utf-8") print "每一個", s app[colnames[i]] = s list.append(app) print row print list return listlistdata=excel_table_byindex("E:\py\\alwaystry\sign_up.xlsx",0)

 

在開頭加了#coding:utf-8 ,就已經是utf-8格式的了,所以能處理中文。
列印print "每一個", s 的時候,列印出來是   每一個 二毛a 
print row 列印出來是[u‘\u4e8c\u6bdba‘,...
print list 列印出來就是[{u‘nickname‘: u‘\u4e8c\u6bdba‘..., 所有的行資料。
當初的我只看到了Unicode編碼就以為他是列印不了中文了,其實是list不能顯示。現在想來,還是太嫩

 

 

在漫長的探索中,我知道了str和Unicode

(我看著覺得不錯的網址http://wklken.me/posts/2013/08/31/python-extra-coding-intro.html)

反正就是

str  -> decode(‘str的編碼格式‘) -> unicode

unicode -> encode(‘你要的格式‘) -> str

要查看編碼格式,就print chardet.detect(listdata[i][‘nickname‘])判斷字元編碼格式當然還是要import chardet的

他有時候會報ValueError: Expected a bytes object, not a unicode object錯,那也就知道他是什麼編碼格式了。

還是這樣吧,直接列印格式:print type(listdata[i][‘realname‘])列印輸出<type ‘unicode‘>,說明人家已經是unicode,那你就把chardet.detect()刪掉就好。

UTF-8是Unicode的實現方式之一/utf8是對unicode字元集進行編碼的一種編碼方式。(當時做筆記記下來的,我覺得這兩句話還是蠻好理解的)

如果,很不慎,你走到了和我當初一樣的境地,早早的把encode,就是注釋掉的那兩句。

提示UnicodeDecodeError: ‘utf8‘ codec can‘t decode byte 0xe4 in position 0: unexpected end of data等等,不妨嘗試一下decode。如果是下拉框匹配的情況,可以先decode再encode試試,下面代碼最後一行。

 

整體大概代碼如下

#輸入網址address = raw_input(‘Enter location: ‘)if len(address) < 1:    print "error"url = address#放你的設定檔profile_dir = r"C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\5cmfbcqp.default"profile = webdriver.FirefoxProfile(profile_dir)driver = webdriver.Firefox(profile)#開啟exceldef open_excel():    try:        data = xlrd.open_workbook(file)        return data    except Exception as e:        print (str(e))def excel_table_byindex(file,colnameindex = 0,by_index= 0):    data = open_excel(file)    table = data.sheets()[by_index]    nrows = table.nrows    #行    colnames = table.row_values(colnameindex)    #列內容    list=[]    for rownum in range(1, nrows):        row = table.row_values(rownum)        if row:            app = {}            for i in range(len(colnames)):                s = row[i]                if isinstance(s, unicode):                    s = row[i].encode("utf-8")                print s                app[colnames[i]] = s            list.append(app)    print (list)    return list#通過css判斷是否存在,你也可以用if elsedef judgewithcss(css):    try:        driver.find_element_by_css_selector(css)    except:        return False    return Truelistdata=excel_table_byindex("E:\sign_up.xlsx",0)if(len(listdata)<0):    assert 0,u"資料異常"for i in range(0, len(listdata)):    driver.get(url)    #暱稱,這是個input    if judgewithcss("#nickname") == True:        nickname = driver.find_element_by_id("nickname")        nickname.clear()        print chardet.detect(listdata[i][‘nickname‘])        nickname.send_keys(listdata[i][‘nickname‘].decode("utf-8"))    #血型,這是個select    if judgewithcss("#blood") == True:        blood = driver.find_element_by_id("blood")        # 以下3種也能判斷出格式        # print isinstance(listdata[i][‘blood‘], unicode)        # print isinstance(listdata[i][‘blood‘], str)        # print type(listdata[i][‘blood‘])        print chardet.detect(listdata[i][‘blood‘])        Select(blood).select_by_value(listdata[i][‘blood‘].decode("windows-1252").encode("windows-1252"))

 

python+selenium excel中文讀取填充到網頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.