Python scrapy爬取京东,百度百科出现乱码,解决方案

Python scrapy爬取京东 百度百科出现乱码 解决方案

 

十分想念顺店杂可。。。

 

抓取百度百科,出现乱码

 
在这里插入图片描述
 

把页面源码下载下来之后,发现全是乱码,浏览器打开

 
在这里插入图片描述
 

但是浏览器链接打开就没有乱码

 
在这里插入图片描述 

以下是浏览器里面的源码

 
在这里插入图片描述

 
 

到这一步说明我们下载网页源码,保存的时候出了问题找了好久,才知道是编码问题,以下为解决方案

 

# -*- coding: utf-8 -*-
# @Time    : 2019/5/13 15:49
# @Author  : 甄超锋
# @Email   : 4535@sohu.com
# @File    : asd.py
# @Software: PyCharm
import requests

url = "https://baike.baidu.com/item/%E6%9D%8E%E5%B9%BC%E6%96%8C/7850567#1"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
    "Host": "baike.baidu.com",
    "Connection": "keep-alive",
}

response = requests.get(url=url, headers=headers)
text_iso_by = bytes(response.text, encoding="ISO-8859-1")
text_iso = text_iso_by.decode("utf-8")
with open("1.html", "w", encoding="utf-8") as f:
    f.write(text_iso)

 

运行后用浏览器打开 1.html 文件,结果如下:

 
在这里插入图片描述
 

至此乱码解决,喜欢请收藏,谢谢

 

pythonQQ交流群:785239887

 

posted @ 2019-05-14 16:41  甄超锋  阅读(642)  评论(1编辑  收藏  举报