码迷,mamicode.com
首页 > 编程语言 > 详细

寒假学习进度-7(Python爬虫)

时间:2020-02-04 10:37:33      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:错误   ase   第三方   pip   code   学习   命令   https   response   

1.使用Python自带的urllib爬取一个网页的代码

# -*- coding: UTF-8 -*-

from urllib import request

if __name__ == "__main__":
    response = request.urlopen("https://www.cnblogs.com/")
    html = response.read()
    html = html.decode("utf-8")
    print(html)

通过request的URLopen向https://www.cnblogs.com/发送请求,返回的数据保存在response中

html.decode("utf-8”)对返回的数据进行解码(decode)

通过pip install chardet命令下载chatdet,通过chardet这个第三方库可以自动获取目标网页的编码

# -*- coding: UTF-8 -*-
from urllib import request
import chardet

if __name__ == "__main__":
    response = request.urlopen("https://www.cnblogs.com/")
    html = response.read()
    charset = chardet.detect(html)
    print(charset)

urllib是学习python爬虫需要掌握的最基本的库,它主要包含四个模块:

  • urllib.request基本的HTTP请求模块。可以模拟浏览器向目标服务器发送请求。
  • urllib.error 异常处理模块。如果出现错误,可以捕捉异常。
  • urllib.parse 工具模块。提供URL处理方法, 比如对URL进行编码和解码。
  • urllib.robotpaser 用来判断哪些网站可以爬,哪些网站不可以爬。

寒假学习进度-7(Python爬虫)

标签:错误   ase   第三方   pip   code   学习   命令   https   response   

原文地址:https://www.cnblogs.com/liujinxin123/p/12258385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!