最近在爬一个网站时,发现我需要的数据,存放在某个 <script></script>
标签内,虽然是字符串的形式,但是格式是 json,这样我就很好处理,只需要用 lxml 获取到 <script></script>
标签内容,再用 python 里面的 json.loads(str)
即可转换为 json,但是在实际过程中遇到了错误。
报错如下:1
ValueError Invalid control character at line 1 column xx (char xx)
经过搜索,发现两种方法来处理
- replace 掉 invalid 字符
思路:报错中提示了,invalid 字符是在 char xx
的位置,你可以直接打印出来,你会看到字符是\r
或者是\n
,然后替换掉.
处理:
1 | json.loads(s.replace('\r\n', '')) |
或者对字符进行转义(escape)
1 | json.loads(s.replace('\r\n', '\\r\\n')) |
- 在
json.loads
时,使用strict=False
参数
1 | json.loads(json_str, strict=False) |
对于这个参数的解释,可以在 https://docs.python.org/2/library/json.html 查看,如下所示:
If strict is false (
True
is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including ‘\t
‘ (tab), ‘\n
‘, ‘\r
‘ and ‘\0
‘.
如果 strict 参数为 false 时(默认是
True
), 字符串内的控制字符将被接受. 在此上下文中的控制字符,是字符代码在 0-31 范围内的控制字符, 包含 ‘\t
‘ (tab), ‘\n
‘, ‘\r
‘ 和 ‘\0
‘.