日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Python爬虫中文乱码问题(爬虫乱码)

發布時間:2025/3/15 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python爬虫中文乱码问题(爬虫乱码) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在輸出內容時,出現如下圖的情況:

解決爬蟲中文亂碼的步驟 網址編碼為gbk

  • 查看網頁源代碼的head部分的編碼:
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">,發現網頁編碼為gbk類型
  • 利用requests庫的方法查看默認輸出的編碼類型
  • import requestsurl = 'https://chengdu.chashebao.com/yanglao/19077.html'response = requests.get(url) print(response.encoding)

    輸出結果為編碼ISO-8859-1,并不是原網頁的編碼類型。

    ? ? 3. 利用requests庫改變輸出結果的編碼

    import requestsurl = 'https://chengdu.chashebao.com/yanglao/19077.html'response = requests.get(url) response.encoding = 'gbk' print(response.encoding)

    輸出結果為編碼gbk,與原網頁保持一致。

    基于以上三個步驟,即可解決爬蟲中文亂碼問題。

    代碼

    import requestsdef get_html(url):try:response = requests.get(url)response.encoding = 'gbk' # 改變編碼print(response.encoding)html = response.textreturn htmlexcept:print('請求網址出錯')url = 'https://chengdu.chashebao.com/yanglao/19077.html' html = get_html(url) print(html)

    效果展示如下圖所示:

    解決爬蟲中文亂碼的步驟 網址編碼為utf-8

    對于有些網頁編碼為utf-8的網址,輸出事發現中文為亂碼,此時我們需要進行兩次重編碼。

    response = requests.get(url, headers=headers) response.encoding = 'GBK' response.encoding = 'utf-8'

    解決爬蟲中文亂碼的步驟 網址編碼為gb2312

    response.encoding = 'GBK'

    ?

    總結

    以上是生活随笔為你收集整理的Python爬虫中文乱码问题(爬虫乱码)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。