爬蟲「Python」:解決網絡爬蟲返回文本中中文顯示“\uxxxx”的問題

一、問題描述

我們在網絡爬蟲時常常遇到好不容易爬到了想要的內容,結果文本中中文顯示“\uxxxx”的問題,這裏展示我遇到的情況:

<html>
<head></head>
<body>
    <pre style="word-wrap: break-word; white-space: pre-wrap;">
        {"code":200,
        "msg":"success",
        "data":{
            "recommend_card_num":0,
            "count":{ "all":8,"enable":8,"draft":0,"deleted":0,"private":0,"audit":0,"original":0},
            "list":[{"ArticleId":"104551659","Title":"Python\uff1a\u4e00\u6b21\u767b\u5f55\uff0c\u89e3\u51b3\u722c\u53d6\u6dd8\u5b9d\u5546\u54c1\u8bc4\u4ef7\u7e41\u6742\u7684\u95ee\u9898\u2014\u2014\u7b80\u8ff0 Headers \u7684\u4f7f\u7528","PostTime":"2020\u5e7402\u670828\u65e5 12:28:23","ViewCount":"13","CommentCount":"0","CommentAuth":"2","IsTop":"0","Status":"1","UserName":"qq_41297934","Type":"1","is_vip_article":false,"editor_type":0,"is_recommend":false}],
            "total":8,"list_status":"all","page":1,"size":20}}
    </pre>
</body>
</html>

我們可以看到在 Html<body> 標籤中,數據格式爲 json 的格式,其中 Title 和 PostTime 屬性存在中文編碼異常的問題,下面我介紹兩種解決方案,讀者可根據自己實際問題有選擇性的採用方案。

二、解決方案

(一)json.loads(str)方法

1. 我們獲取 <body> 標籤內的 json 內容,交由 json.loads(str) 方法來解決編碼問題,示例代碼如下:

import json
import re

# 文件存儲在../data/1.html
with open('../data/1.html', 'r') as f:
    html = f.read()
    # 通過正則表達式來匹配json內容
    html_json = re.findall(r'>(\{.+?})<', html.replace('\n', '').replace(' ', ''))[0]

    # 輸出json對象
    print(json.loads(html_json))

2. 結果

{'code': 200, 'msg': 'success', 'data': {'recommend_card_num': 0, 'count': {'all': 8, 'enable': 8, 'draft': 0, 'deleted': 0, 'private': 0, 'audit': 0, 'original': 0}, 'list': [{'ArticleId': '104551659', 'Title': 'Python:一次登錄,解決爬取淘寶商品評價繁雜的問題——簡述Headers的使用', 'PostTime': '2020年02月28日12:28:23', 'ViewCount': '13', 'CommentCount': '0', 'CommentAuth': '2', 'IsTop': '0', 'Status': '1', 'UserName': 'qq_41297934', 'Type': '1', 'is_vip_article': False, 'editor_type': 0, 'is_recommend': False}], 'total': 8, 'list_status': 'all', 'page': 1, 'size': 20}}

(二)eval(expression)方法

1. 使用正則表達式生成“\uxxxx”異常列表 u_list,然後使用 eval 函數對列表中每一個元素進行運算,生成正常列表 n_list 。然後使用 replace 全部替換。

import re

with open('../data/2.html', 'r') as f:
    html = f.read()
    old_html = html.replace('\n', '').replace(' ', '')

    # 通過正則表達式匹配'\uxxxx',返回全部'\u'列表,生成u_list
    u_list = re.findall(r'(\\u\w+)', old_html)

    # 使用eval()函數執行字符串表達式(這裏將'\uxxxx'視爲字符串表達式),返回正常列表,生成n_list
    n_list = []
    for i in u_list:
        i = "u'" + i + "'"
        n_list.append(eval(i))

    # 遍歷u_list和n_list,替換原html中的內容
    new_html = old_html
    for i in range(len(u_list)):
        new_html = new_html.replace(u_list[i], n_list[i])
    print(new_html)

2. 結果

<html><head></head><body><prestyle="word-wrap:break-word;white-space:pre-wrap;">{"code":200,"msg":"success","data":{"recommend_card_num":0,"count":{"all":8,"enable":8,"draft":0,"deleted":0,"private":0,"audit":0,"original":0},"list":[{"ArticleId":"104551659","Title":"Python:一次登錄,解決爬取淘寶商品評價繁雜的問題——簡述Headers的使用","PostTime":"2020年02月28日12:28:23","ViewCount":"13","CommentCount":"0","CommentAuth":"2","IsTop":"0","Status":"1","UserName":"qq_41297934","Type":"1","is_vip_article":false,"editor_type":0,"is_recommend":false}],"total":8,"list_status":"all","page":1,"size":20}}</pre></body></html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章