开发者社区> 问答> 正文

Python3 爬html编码问题?报错

我使用的是BeautifulSoup+urllib 环境:Python3.5.2

该网站使用UTF-8编码

百度、谷歌上的方法我都试过了,但是还都是乱码:X{Oã8ÿ€ý>Ÿt…•ÓeW®ÉªŽp ÁÑ£eٓNŠÜÄi

 

相关代码如下    

# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import urllib.request
import urllib
import io  
import sys  
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='UTF-8')  

def get_token(requrl,header):
    req = urllib.request.Request(url=requrl,headers=header)
    
    response = urllib.request.urlopen(req)
    print(type(response))
    
    print (response.getcode()) 
    
    the_page = response.read()
    
    print(len(the_page))
    
    soup = BeautifulSoup(the_page,"html.parser",from_encoding="iso-8859-15")
    
    print(soup.prettify())
    
    
    
    user_token = soup.form.input.input.input.input["value"] #get the user_token
    return user_token


user_token = get_token(requrl,header)

        测试了很久,觉得问题主要就是出现在   the_page = response.read()  这里,read()返回一个bytes类,然后这个东西只能用iso-8859-15解码才不报错,但是试了很多办法,依旧输出的乱码,求解

这个回答很有参考意义,和我情况很像,但是按他的方法还是不对https://www.oschina.net/question/1012422_145865

哪位大表哥帮帮我~~~

展开
收起
爱吃鱼的程序员 2020-06-08 17:25:26 444 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    网页源码标识了utf-8,应该按照utf-8解码吧

    2020-06-08 17:25:44
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载