【发布时间】:2018-01-27 01:46:09
【问题描述】:
我在这里认输。我正在尝试将使用scrapy(注入的javascript)从网站的源代码中抓取的字符串转换为json,以便我可以轻松访问数据。问题归结为解码错误。我尝试了各种编码、解码、转义、编解码器、正则表达式、字符串操作,但没有任何效果。哦,使用 Python 3。
我缩小了字符串(或至少部分)的罪魁祸首
scraped = '{"propertyNotes": [{"title": "Local Description", "text": "\u003Cp\u003EAPPS\u003C/p\u003E\n\n\u003Cp\u003EBig Island Revealed (comes as app or as a printed book)\u003C/p\u003E\n\n\u003Cp\u003EAloha Big Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island Smart Maps (I like this one a lot)\u003C/p\u003E\n\n\u003Cp\u003EBig Island Adventures (includes videos)\u003C/p\u003E\n\n\u003Cp\u003EThe descriptions of beaches are helpful. Suitability for swimming, ease of access, etc. is included. Some beaches are great for picnics and scenic views, while others are suitable for swimming and snorkeling. Check before you go.\u003C/p\u003E"}]}'
scraped_raw = r'{"propertyNotes": [{"title": "Local Description", "text": "\u003Cp\u003EAPPS\u003C/p\u003E\n\n\u003Cp\u003EBig Island Revealed (comes as app or as a printed book)\u003C/p\u003E\n\n\u003Cp\u003EAloha Big Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island Smart Maps (I like this one a lot)\u003C/p\u003E\n\n\u003Cp\u003EBig Island Adventures (includes videos)\u003C/p\u003E\n\n\u003Cp\u003EThe descriptions of beaches are helpful. Suitability for swimming, ease of access, etc. is included. Some beaches are great for picnics and scenic views, while others are suitable for swimming and snorkeling. Check before you go.\u003C/p\u003E"}]}'
data = json.loads(scraped_raw) #<= works
print(data["propertyNotes"])
failed = json.loads(scraped) #no work
print(failed["propertyNotes"])
不幸的是,我无法找到一种方法让 scrapy/splash 将字符串作为原始字符串返回。因此,不知何故,我需要让 python 在加载 json 时将字符串解释为原始字符串。请帮忙
更新:
适用于该字符串的是json.loads(str(data.encode('unicode_escape'), 'utf-8')) 但是,它不适用于较大的字符串。我这样做的错误是 JSONDecodeError: Invalid \escape 在较大的 json 字符串上
【问题讨论】:
-
原始字符串是语言的句法特性,而不是运行时特性。您是从网站生成 Python source 吗? (请说不...)
-
原始或非原始仅与字符串文字有关。对于您从其他地方读取的数据,这种区别是没有意义的。您需要向我们展示您在读取数据时遇到的失败,而不是文字数据。
-
那行不通。适用于该字符串的是
json.loads(str(data.encode('unicode_escape'), 'utf-8'))但是,它不适用于较大的字符串。我这样做的错误是较大的 json 字符串上的JSONDecodeError: Invalid \escape。 see it here on repl.it -
使用起来有点困难,但如果我运行
data_feed = json.loads(data.encode('unicode_escape').decode('utf-8')),它看起来就像读取为无效的 json -
如果您将字符串中的数据粘贴到 jsonlint.com 中,则会将其标记为有效。那是在任何编码/解码之前。
标签: python json python-3.x character-encoding