鱼C论坛

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

python爬取也面乱码

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

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

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

x
亲们,第一次发帖,最近在研究python爬虫,在爬取页面前,已分析页面数据,页面中明确标识编码为UTF-8,在存储时也标注了encode为utf-8,但页面认为乱码,请问如何解决呢?
  1. import requests
  2. import chardet   #用于测试网站编码
  3. from bs4 import BeautifulSoup
  4. url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
  5. head = {
  6.     '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'
  7. }


  8. r = requests.get(url=url,headers=head).text
  9. r_date = requests.get(url=url,headers=head).content
  10. print(chardet.detect(r_date))
  11. with open('./sgyy.html','w',encoding='UTF-8') as fp:
  12.     fp.write(r)
  13. 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>
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

  2. url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
  3. head = {
  4.     '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'
  5. }
  6. r = requests.get(url=url, headers=head)
  7. r.encoding = 'utf-8'
  8. with open('test.html', 'w', encoding='utf-8') as f:
  9.     f.write(r.text)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-7-20 21:25:13 | 显示全部楼层
呃, 这个应该不是乱码, 就是HTML用于表达特殊字符的方式, 如小于号就是&lt(实际<)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-21 14:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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