解决python爬虫中文乱码问题

今天在用python爬取网页数据时中文显示乱码,最终发现是目标网页编码与python默认编码‘utf-8’不一致导致的。下面把解决方法与大家分享。

step1:查看目标网页编码方式

在各种浏览器打开的任意页面上使用F12功能键,即可使用开发者工具,在窗口console标签下,键入“document.charset” 即可查看网页的编码方式。如网页链接: http://www.tianqihoubao.com/aqi/lanzhou-201812.html的编码为“GBK”。
在这里插入图片描述

step2:对目标网页转码

url="http://www.tianqihoubao.com/aqi/lanzhou-201812.html"
try:
    html=urlopen(url)
except HTTPError as e:
    print (e)
else:
    #目标网页编码为'GBK',python默认编码为'utf-8',为解决中文乱码问题,对目标网页进行解码再编码
    bsobj=BeautifulSoup(html.read().decode('GBK').encode('utf-8') )

step3:爬取数据并保存

# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
import urllib.parse
import pandas as pd

url="http://www.tianqihoubao.com/aqi/lanzhou-201812.html"
try:
    html=urlopen(url)
except HTTPError as e:
    print (e)
else:
    #目标网页编码为'GBK',python默认编码为'utf-8',为解决中文乱码问题,先对目标网页进行解码再编码
    bsobj=BeautifulSoup(html.read().decode('GBK').encode('utf-8') )
#获取标签为tr的数据
data=bsobj.findAll('tr')
con=[]
#取出表头
for i in data[0:1]:
    title=i.get_text().strip().split("\n\n")
print (title)
#取表格中的内容
for i in data[1:]:
    contents=i.get_text()
    con.append(contents.replace(" ","").replace("\n\r","").replace("\r\n","").strip().split("\n"))
#将数据放到DataFrame中并写入csv文件保存
air_data=pd.DataFrame(con,columns=title)
print (air_data)
air_data.to_csv('air.csv',index=None)

保存的数据详情:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ziyin_2013/article/details/85457903