python - 爬虫获取网站数据,出现乱码怎么解决。

 徐徐回忆_545 发布于 2022-10-27 14:50
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2
import re
import HTMLParser

class WALLSTREET:
    def __init__(self, baseUrl):
        self.url = baseUrl
    def get_html_content(self):
        url = self.url
        response = urllib2.urlopen(url)
        str = response.read()
        print str
baseUrl="https://wallstreetcn.com/live/global" #华尔街见文url
ws = WALLSTREET(baseUrl)
ws.get_html_content()

以上是代码,写的很简单,但是print出来的是乱码
尝试了 print str.decode(“utf-8“”)
但是报错
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte

4 个回答
  • 应该是encode吧

    2022-10-28 13:36 回答
  • 这儿应该是encode不是decode,而且你的变量名居然是跟内置关键字名字一样

    2022-10-28 13:37 回答
  • 推测用的是sublime text?
    参考这个

    2022-10-28 13:38 回答
  • str = response.read()这句有两个问题:
    1、str是内置关键字必须更改为其他变量名
    2、查看网页源代码的编码方式,如果为utf-8在read()后加.decode('utf-8'),若为其他可以相应解码

    小建议这种小程序写个函数会比用类来更加方便,无论是使用还是实现

    2022-10-28 13:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有