天天看點

python在處理CSV檔案時,字元串和清單寫入的差別概述 代碼:CSV檔案: 注意:

概述

  Python在處理CSV檔案時,如果writerow的對象是<type 'unicode'>字元串時,寫入到CSV檔案時将會出現一個字元占一個單元格的情況:

python在處理CSV檔案時,字元串和清單寫入的差別概述 代碼:CSV檔案: 注意:

  

  但是将字元串轉換為清單類型時,進行writerow寫入即可實作,writerow一個清單隻占一個單元格:

python在處理CSV檔案時,字元串和清單寫入的差別概述 代碼:CSV檔案: 注意:

 代碼:

#encoding=utf-8
#不打開浏覽器進行操作
import sys,csv,codecs
import time
from lxml import etree
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_argument("headless")
driver = webdriver.Chrome(chrome_options=option)
# driver = webdriver.Chrome()
driver.get("https://www.kanzhun.com/xs/?ka=head-salary")
print([driver.title])
#打開CSV檔案
csvfile=codecs.open('C:\Users\Desktop\test.csv','wb','gbk')
writer = csv.writer(csvfile)
writer.writerow(driver.title)
#擷取城市工資排名
aa=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[1]/dd/ul/li/i')
bb=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[1]/dd/ul/li/a')
cc=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[1]/dd/ul/li/span')
print('======地區工資排行(TOP10)======')
writer.writerow([u'======地區工資排行(TOP10)======'])
for (i,o,p) in zip(aa,bb,cc):
    i = i.text
    o = o.text
    p = p.text
    print(type(p))
    ss = [i, o, p]
    writer.writerow(ss)
    print(i+'...'+o+'...'+p)
#擷取公司工資排名
aa=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[2]/dd/ul/li/i')
bb=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[2]/dd/ul/li/a')
cc=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[2]/dd/ul/li/span')
print('======公司工資排行(TOP10)======')
writer.writerow([u'======公司工資排行(TOP10)======'])
for (i,o,p) in zip(aa,bb,cc):
    i = i.text
    o = o.text
    p = p.text
    ss = [i, o, p]
    writer.writerow(ss)
    print(i+'...'+o+'...'+p)
#擷取職位工資排名
aa=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[3]/dd/ul/li/i')
bb=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[3]/dd/ul/li/a')
cc=driver.find_elements_by_xpath('/html/body/div/section[1]/div[3]/dl[3]/dd/ul/li/span')
print('======職位工資排行(TOP10)======')
writer.writerow([u'======職位工資排行(TOP10)======'])
for (i,o,p) in zip(aa,bb,cc):
    i = i.text
    o = o.text
    p = p.text
    ss = [i,o,p]
    writer.writerow(ss)
    print(i+'...'+o+'...'+p)
csvfile.close()
driver.quit()
           

  

CSV檔案:

python在處理CSV檔案時,字元串和清單寫入的差別概述 代碼:CSV檔案: 注意:

 注意:

其中開頭的reload(sys)和打開csv檔案時的‘gbk’都是輔助解決字元編碼問題的。

轉載于:https://www.cnblogs.com/phyger/p/9561405.html