python - 打印时显示日语字符,但保存到 csv 时不显示

标签 python web-scraping beautifulsoup

我编写了一个 beautifulsoup 脚本,可以抓取日语 HTML。一切似乎都正常,我收到零错误消息。当我打印时我得到:

連鎖に打ち勝たねばならない」と述べ拍手を浴び etc

但是在同一个脚本中,当我将输出保存在 csv 中时,我得到:

\u5ddd\u3001\u6ce2\u4f50\u5834\uff13\u7279\u6d3e\u54e1\u304c\u8a71\u3057\u5408 etc

我认为问题出在代码的写入 csv 部分,但我不知道该怎么做。

代码如下:

def processData( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    f.close()
    soup = BeautifulSoup(page, 'html.parser')
    metaData = soup.find_all("div", {'class': 'detail001'})
    one = [ ]
    for html in metaData:
        text = BeautifulSoup(str(html).strip().replace("\n", ""),features="html.parser")
        text = text.get_text()
        one.append(text.strip())
    csvfile = open(dir2 + ".csv".encode("utf-8"), 'ab')
    writer = csv.writer(csvfile)
    for ones in zip(one):
        writer.writerow([one])
    csvfile.close()
dir1 = "/home/sveisa/"
dir2 = "test2"
dir = dir1 + dir2
csvFile = dir2 + ".csv"
csvfile = open(csvFile.encode("utf-8"), 'w')
writer = csv.writer(csvfile)
writer.writerow(["one"])
csvfile.close()
fileList = os.listdir(dir)
totalLen = len(fileList)
for htmlFile in fileList:
    path = os.path.join(dir, htmlFile)
    processData(path)

我使用的是 Ubuntu。

最佳答案

这是关于需要分配给您的csvencoding=,如下所示:

with open("data.csv", 'w', encoding="UTF-8") as f:
    writer = csv.writer(f)
    writer.writerow(
        "\u5ddd\u3001\u6ce2\u4f50\u5834\uff13\u7279\u6d3e\u54e1\u304c\u8a71\u3057\u5408")

输出内容:

川、波佐場3特派員が話し合

关于python - 打印时显示日语字符,但保存到 csv 时不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61170388/

相关文章:

python - Jinja2 html按钮: Catch POST on different pages

python - 我在抓取的 JSON 中遇到 KeyError

python - 为什么它不允许我将列表转换为字符串?

python - 从 BeautifulSoup 结果集中提取 <li> 标签

python - Sodapy 客户端的 API 数据读取超时错误

python - 使用cherrypy发出HTTP请求

python - 如何提取div标签中的强元素

python - 我怎样才能在 <span> </span> 使用 python splinter lib 之间获取文本

python - 美丽汤提取物标签删除文字

python - 制表符长度