urllib处理包的简单使用

我们可以使用urllib.request.urlopen()这个接口函数就可以打开一个网站,读取打印信息

你可以现在终端使用python

from urllib import request

if __name__ == "__main__":

   response = request.urlopen("http://fanyi.baidu.com")

  html = response.read()

   print(html)

这时候打印出来的应该是解码之前,看着特别别扭

所以你就需要打印出来的网页信息进行解码

要想知道编码方式,可能有点费事

所以此时就有可能要用到一个叫chardet的第三方库了:

终端安装:

pin install chardet

然后输入一下代码:

from urllib import request

import chardet

  if __name__ == "__main__":

  response = request.urlopen("http://fanyi.baidu.com/")

  html = response.read()

  charset = chardet.detect(html)

  print(charset)

打印结果如下:

当我们知道编码格式后就可以进行解码了很简单:

from urllib import request

 if __name__ == "__main__":

  response = request.urlopen("http://www.fanyi.baidu.com/")

  html = response.read()

  html = html.decode("utf-8")

  print(html)

打印出来后是不是看着简洁多了!!哈哈

posted @ 2018-08-20 14:59  天选之人  阅读(175)  评论(0编辑  收藏  举报