1. 程式人生 > >python requests返回中文亂碼

python requests返回中文亂碼

ons enc lxml nco res gb2 main def bs4

  最近在使用python爬取高考分數線時,獲得的response裏面輸出了中文亂碼:

from bs4 import BeautifulSoup
import requests

def get_provice_link(url):
    response=requests.get(url)

    print(response.text)
    soup=BeautifulSoup(response.text,lxml)
    print(soup.title)

def main():
    url=http://www.gaokao.com/beijing/fsx/
    get_provice_link(url)

if __name__ == __main__: main()

技術分享圖片

  解決方案是:將response設置編碼格式,一般的如果網頁中沒有標明type格式,一般默認的都是‘ISO-8859-1‘編碼,我們只需要把編碼格式轉為 ‘gb2312‘ 即可

添加一行代碼:下面標紅的,這樣就可以解決。

 response=requests.get(url)
    response.encoding = ‘gb2312‘
    print(response.text)

技術分享圖片

技術分享圖片

python requests返回中文亂碼