Skip to main content
 首页 » 编程设计

python之如何在 python 中处理 unicode 语言

2025年05月04日11mayingbao

我正在编写一个 Python + Selenium 脚本来废弃 Linkedin 网站。
我使用此语句阅读了配置文件摘要,该语句正常工作:

profileDescription = profile.find_element_by_xpath("div/div[1]").text   

我的问题是来自网站的非英语数据。
我正在使用以下代码将从站点收集的数据写入 excel:

with open('search.csv', 'ab') as csvfile: 
    self.liSearchOutWriter = csv.writer(csvfile, delimiter=',') 
    self.liSearchOutWriter.writerow([profileDescription])  

每当描述中包含非英文数据时,它就无法在 excel 中正确显示。我通读了 unicode 和 utf8 资源,但无法掌握它。

谁能帮我理解我应该如何修改我的代码才能正确显示非英语数据?

请您参考如下方法:

在 Python 3.X 中这是开箱即用的支持:

 import csv 
 with open('search.csv', newline='', encoding='utf-8') as csvfile: 
     reader = csv.reader(csvfile) 
     for row in reader: 
         print(row) 

如果您使用的是 Python 2.X,则有一个支持 unicode 的 csv 插件库: unicode-csv

import unicodecsv 
with open('search.csv', newline='', encoding='utf-8') as csvfile: 
    unicodecsv.reader(f, encoding='utf-8'