鱼C论坛

 找回密码
 立即注册
查看: 1053|回复: 2

python爬取也面乱码

[复制链接]
发表于 2021-7-20 10:14:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
亲们,第一次发帖,最近在研究python爬虫,在爬取页面前,已分析页面数据,页面中明确标识编码为UTF-8,在存储时也标注了encode为utf-8,但页面认为乱码,请问如何解决呢?
import requests
import chardet   #用于测试网站编码
from bs4 import BeautifulSoup
url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
head = {
    'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64'
}


r = requests.get(url=url,headers=head).text
r_date = requests.get(url=url,headers=head).content
print(chardet.detect(r_date))
with open('./sgyy.html','w',encoding='UTF-8') as fp:
    fp.write(r)
soup_r = BeautifulSoup(r,'lxml')

爬取结果为:
<!DOCTYPE html>
<html lang="zh">
<head>
        <script type="text/javascript" src="https://ip.ws.126.net/ipquery"></script>
    <script src="/newpage/js/all.js"></script>
    <meta charset="UTF-8">
    <title>&#227;&#128;&#138;&#228;&#184;&#137;&#229;&#155;&#189;&#230;&#188;&#148;&#228;1&#137;&#227;&#128;&#139;&#229;&#133;¨é&#155;&#134;&#229;&#156;¨&#231;o&#191;é&#152;&#133;èˉ&#187;_&#229;&#143;2&#228;1|&#229;&#133;&#184;&#231;±&#141;_èˉ&#151;èˉ&#141;&#229;&#144;&#141;&#229;&#143;¥&#231;&#189;&#145;</title>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-7-20 16:42:32 | 显示全部楼层
import requests

url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
head = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64'
}
r = requests.get(url=url, headers=head)
r.encoding = 'utf-8'
with open('test.html', 'w', encoding='utf-8') as f:
    f.write(r.text)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-7-20 21:25:13 | 显示全部楼层
呃, 这个应该不是乱码, 就是HTML用于表达特殊字符的方式, 如小于号就是&lt(实际<)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-8 22:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表