鱼C论坛

 找回密码
 立即注册
查看: 2748|回复: 6

[已解决]【零基础向】爬虫客第一节课就劝退了!!!

[复制链接]
发表于 2020-3-20 01:12:43 | 显示全部楼层 |阅读模式

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

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

x
  1. import urllib.request
  2. import chardet

  3. response = urllib.request.urlopen("http://www.baidu.com/")
  4. html = response.read()
  5. html = html.decode("utf-8")
  6. # chardet.detect(response) # 这里报错了
  7. print(html)
复制代码



问题来了,

1,chardet报错原因?

2,刚看到旧版的爬虫教程,听说现在都是用request,那教程有更新吗?
最佳答案
2020-3-20 08:04:07
chardet 应该这样用:

  1. import urllib.request
  2. import chardet

  3. response = urllib.request.urlopen("http://www.baidu.com/")    # 这里是 https
  4. html = response.read()
  5. print(chardet.detect(html))
  6. html = html.decode("utf-8")
  7. print(html)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-3-20 02:52:57 | 显示全部楼层
我用python3.6运行,没有问题
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-20 08:04:07 | 显示全部楼层    本楼为最佳答案   
chardet 应该这样用:

  1. import urllib.request
  2. import chardet

  3. response = urllib.request.urlopen("http://www.baidu.com/")    # 这里是 https
  4. html = response.read()
  5. print(chardet.detect(html))
  6. html = html.decode("utf-8")
  7. print(html)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-20 08:49:39 | 显示全部楼层
zltzlt 发表于 2020-3-20 08:04
chardet 应该这样用:

好像也不是。。。改成print还是报错,错误提示TypeError: Expected object of type bytes or bytearray, got: <class 'str'>
百度了一下,是说str对象有一个encode方法,bytes对象有一个decode方法,尝试了一下能run出来
  1. import urllib.request
  2. import chardet

  3. response = urllib.request.urlopen("http://placekitten.com/g/500/300")
  4. responseStr = str(response)
  5. imag = response.read()
  6. with open("cat_image.jpg", "wb") as f:
  7.     f.write(imag)
  8. responseStr = responseStr.encode()
  9. print(chardet.detect(responseStr))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-20 08:52:52 | 显示全部楼层
zltzlt 发表于 2020-3-20 08:04
chardet 应该这样用:

然后我的问题来了,urlopen出来的是bytes对象和str对象怎么确定?就只能看错误提示吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-3-20 09:09:38 From FishC Mobile | 显示全部楼层
zltzlt 发表于 2020-3-20 08:04
chardet 应该这样用:

没事我去翻文档了,已经是半熟鱼油了,不能再做伸手党了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-3-20 13:03:03 | 显示全部楼层
xiaofan1228 发表于 2020-3-20 08:49
好像也不是。。。改成print还是报错,错误提示TypeError: Expected object of type bytes or bytearray,  ...

read() 方法返回的一般都是 bytes 呀
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-28 00:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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