【问题标题】:Writing to JSON - Converting \u00a3 to £写入 JSON - 将 \u00a3 转换为 £
【发布时间】:2019-03-25 16:30:43
【问题描述】:

我正在使用 Selenium 和 python 来抓取网站。我正在抓取一些“£”字符,但我得到的是:\u00a3,在写入 JSON 时(它们显示为“£”,我将它们打印到终端)。

我知道它们是 Unicode,我需要它们为 UTF8 (?)。我已经尝试了一些我在 SO 上找到的东西,但都没有取得太大的成功。

我已经尝试过 .replace (.replace('\u00a3', '£') - 但是我没有取得太大的成功。

如何让字符看起来像“£”而不是 \u00a3

这是打印不正确的行。如果您想查看我的完整代码,请告诉我。

price = page.find_element_by_class_name('header_tags').text

【问题讨论】:

  • 你可能想看看编码

标签: python json selenium selenium-webdriver utf-8


【解决方案1】:

如果您使用的是json.dump()json.dumps(),请尝试设置ensure_ascii=False

【讨论】:

    【解决方案2】:

    你可以像下面这样对字符串进行编码

    s = 'This is a Pound sign \u00a3'
    s.encode('utf8')
    print(s)
    

    输出

    This is a Pound sign £

    【讨论】:

      【解决方案3】:

      打印时需要调用text("utf-8"),如下:

      print(page.find_element_by_class_name('header_tags').text("utf-8"))
      

      但这个问题也可能出现在某些行。因此,按照最佳实践,Python 文件的开头为:

      # -*- coding: UTF-8 -*-
      

      一个例子:

      from selenium import webdriver
      # other lines of code
      price = page.find_element_by_class_name('header_tags').text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-24
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        • 2020-04-28
        • 1970-01-01
        • 2014-02-17
        相关资源
        最近更新 更多